There is a list of all_users, in this list there are dictionaries - person, a person has a parameter called user_id. I don't want to add dictionaries with the same user_id to the list.

all_users = [] while True: for event in longpoll.listen(): if event.type == VkEventType.MESSAGE_NEW and not (event.from_me): person = dict.fromkeys(['user_id']) person['user_id'] = event.user_id all_users.append(person) for x in all_users: print(x) 

This code assigns the id of the person who wrote the message to the person as the value for the key user_id, later adding the person to the list all_users

  for it in all_users: if it['user_id'] != person['user_id']: all_users.append(person) print("Добавил!") else: print("Этот пользователь уже добавлен") 

Having added this code before I displayed all_users on the screen, I thought that the person with the same user_id would no longer be added to the list, but this code was not executed at all + the entire list was not displayed on the screen.

I can not understand what the problem is. Tell me, please, is it correct if I check for a user_id match, if it is correct, then why does the code stop running? and if wrong, how can the implementation be done differently?

 all_users_ids = {user['user_id'] for user in all_users} if user_id not in all_users_ids: person = {'user_id': user_id, 'link': link} all_users.append(person) print("Добавил") for x in all_users: print(x) 

    2 answers 2

    Try this:

     all_users = [] while True: for event in longpoll.listen(): if event.type == VkEventType.MESSAGE_NEW and not (event.from_me): user_id = event.user_id # Просто подготовил отдельно набор всех айдишники пользователей # Для этого я использовал синтаксис set comprehension # (можете погуглить, что это такое) all_users_ids = {user['user_id'] for user in all_users} # Проверяю, содержится ли user_id # в заранее подготовленном наборе айдишников. # Ключевое слово in позволяет проверить наличие элемента # в списке или множестве без всякого цикла if user_id not in all_users_ids: # Просто создал словарь с ключом 'user_id' # И значением из переменной user_id # Это просто другой способ записи для # {'user_id': user_id} person = dict(user_id=user_id) all_users.append(person) for x in all_users: print(x) 

    About your code. Here in this piece

     for it in all_users: if it['user_id'] != person['user_id']: all_users.append(person) 

    you apparently want to check that a user with such user_id not contained in all_users . But this piece of code will not work that way. Instead, it checks that there are different elements in user_id . And since at first you don’t have any elements there at all - neither different, nor coinciding, the addition never works at all.

    And it’s good that it doesn’t work - because if you already had elements there, it would add many times a new one - according to the number of existing ones and the list would quickly begin to swell to indecent sizes. (If I do not confuse anything, there would be a power growth, that is, after a few dozen users, the list would have eaten all the memory in your computer)

    • Thank you very much, the code works, but could you explain what this piece of code does? From 6 to 8 line - Dima
    • And one more question. The code is attached at the top. At the first iteration, the user is added, the inscription "added" is displayed and the entire list of all_users is displayed, during further iterations the inscription "added" is not displayed in the console and the person is not added to all_users, but the entire list of all_users is displayed. What is it like? everything is written in one condition, why are some lines executed and others not? - Dima
    • @ Dima, I added comments with explanations to my code - Xander

    If I understand you correctly:

     all_users = [] listID = [ 1, 2, 3, 4, 1, 2, 5 ] for i in listID: if {'user_id': i} in all_users: print("Этот пользователь уже добавлен") else: all_users.append({'user_id': i}) print("Добавил!") Добавил! Добавил! Добавил! Добавил! Этот пользователь уже добавлен Этот пользователь уже добавлен Добавил! print(all_users) [{'user_id': 1}, {'user_id': 2}, {'user_id': 3}, {'user_id': 4}, {'user_id': 5}]