N. J
N. J

Reputation: 480

Check if value already exists in dictionary and append the value to list

I've been following this: check-if-value-already-exists-within-list-of-dictionaries.
However, I don't just want to check if the value already exists, I also want append that value if it exists to my exists_list and to not_exists_list if it doesn't. The problem is that I cannot "get" that value with the method I have been using because of the scope of the variable.

e.g

list_dict = [ { 'name': 'Lucas', 'addr': 4 }, { 'name': 'Gregor', 'addr': 44 }]
list_dict_comp = [ { 'name': 'Lucas', 'address': 'Lucas_XXASD' }, { 'name': 'Gregor', 'address': 'Gregor_ASDXX', { 'name': 'Iz', 'address': 'IZ_KOS' } }]

exists_list = []
not_exists_list = []

for i in list_dict:
  if not any(a['name'] == i['name'] for a in list_dict_comp):
    not_exists_list.append(a['address'])   # <--- 'a' is not defined, because local scope.
  else:
    exists_list.append(a['address'])

ERROR

Traceback (most recent call last):
  File "python3.py", line 11, in <module>
    exists_list.append(a['address'])
NameError: name 'a' is not defined

EXPECTED OUTPUT

not_exists_list['IZ_KOS']

exists_list['Lucas_XXASD', 'Gregor_ASDXX']

Upvotes: 1

Views: 1898

Answers (2)

Arifa Chan
Arifa Chan

Reputation: 1017

From your edited question and added expected output, you only need to iterate over list_dict_comp and append i['address'] to the correspnding list.

list_dict = [ { 'name': 'Lucas', 'addr': 4 }, { 'name': 'Gregor', 'addr': 44 }]
list_dict_comp = [ { 'name': 'Lucas', 'address': 'Lucas_XXASD' }, { 'name': 'Gregor', 'address': 'Gregor_ASDXX'}, { 'name': 'Iz', 'address': 'IZ_KOS' } ]


exists_list = []
not_exists_list = []

for i in list_dict_comp:
    if not any(a['name'] in i['name'] for a in list_dict):
        not_exists_list.append(i['address'])
    else:
        exists_list.append(i['address'])

print(not_exists_list)
print(exists_list)

# ['IZ_KOS']
# ['Lucas_XXASD', 'Gregor_ASDXX']

Upvotes: 0

Tantary Tauseef
Tantary Tauseef

Reputation: 176

One way is to use a double for loop:

for data in list_dict:
    for data2 in list_dict_comp:
        if data['name'] == data2['name']:
            exists_list.append(data2['address'])
            break

    else:
        not_exists_list.append(data2['address'])

Upvotes: 2

Related Questions