Home > Enterprise >  Unable to remove all dicts from list in a for loop
Unable to remove all dicts from list in a for loop

Time:06-27

I'm trying to compare 2 JSONs with structure as follows: dict with list of dicts. The idea was to remove all dicts that match by their contents from list and then check if both lists are empty. If they are empty, values on such key are matching. Else output rest of JSON that didn't match to console\file whatever.

But looks like simply removing dicts doesn't work.

Minimal working code below:

test = { "first" : [{"Name": "Harry", "Age": 18}, {"Name": "Harry", "Age": 17}, {"Name": "Harry", "Age": 19}] ,
"second" : [{"Name": "Harry", "Age": 20}, {"Name": "Harry", "Age": 15}, {"Name": "Harry", "Age": 11}]}

print(test.keys())
for key in test.keys():
    print(key)
    data = test[key]
    data_remove_from = test[key]

    for dict_test in data:
         data_remove_from.remove(dict_test)


    print(data_remove_from)

Code above results in:

dict_keys(['first', 'second'])
first
[{'Name': 'Harry', 'Age': 17}]
second
[{'Name': 'Harry', 'Age': 15}]

Expected outcome:

dict_keys(['first', 'second'])
first
[]
second
[]

I'm very confused, why this doesn't work?

CodePudding user response:

for the expected outcome, You can use the copy() method to replicate a list and leave the original list unchanged like this: data_remove_from = test[key].copy()

  1. full code:
test = {"first": [{"Name": "Harry", "Age": 18}, {"Name": "Harry", "Age": 17},
                  {"Name": "Harry", "Age": 19}],
        "second": [{"Name": "Harry", "Age": 20}, {"Name": "Harry", "Age": 15},
                   {"Name": "Harry", "Age": 11}]}
print(test.keys())
print(test.keys())
for key in test.keys():
    print(key)
    data = test[key]
    data_remove_from = test[key].copy()
    for dict_test in data:
        data_remove_from.remove(dict_test)
    print(data_remove_from)
  • Related