1

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']
N. J
  • 398
  • 2
  • 13
  • Which `a` are you refering to?? You just looked at all `a` in `list_dict_comp`... Please clarify what you want to do. – Thierry Lathuille Oct 08 '22 at 10:37
  • If you want to append values from `list_dict_comp` into the arrays, then iterate over the `list_dict_comp` and append `i` variable not `a`. Also change the check to `any(a['name'] == i['name'] for a in list_dict)`. – Viliam Popovec Oct 08 '22 at 10:41
  • @ThierryLathuille I've already stated what I want to accomplish. I get the desired result by using the `if`-statement, please see link. However, I'm only interested in the `a` value, once the `if`-statement is "finished". – N. J Oct 08 '22 at 11:31
  • What is your expected output? – Arifa Chan Oct 08 '22 at 11:37
  • @ArifaChan Update Description – N. J Oct 08 '22 at 11:42

2 Answers2

2

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'])
0

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']
Arifa Chan
  • 947
  • 2
  • 6
  • 23