Home > Net >  Compare two dictionaries and check if some values do not exist
Compare two dictionaries and check if some values do not exist

Time:12-15

I've got two lists of dictionaries as below:

string1 =[
  {"name": "Tom", "age": 10},
  {"name": "Mark", "age": 5},
  {"name": "Pam", "age": 7},
  {"name": "Weranika", "age": 18}
]
string2 =[  {"name": "Tom", "age": 8},
  {"name": "Mark", "age": 5},
  {"name": "Pam", "age": 7}
]

And I want to print key/value for item which doesn't exists in the second list of dictionary.

In my case output should return:

{"name": "Weranika", "age": 18}

CodePudding user response:

You can iterate over the dictionaries in string1 and check if a name in it exists in the set of names in string2:

names = set(d['name'] for d in string2)
not_in_string2 = [dct for dct in string1 if dct['name'] not in names]

Output:

{'name': 'Weranika', 'age': 18}

CodePudding user response:

def compare(list_dict_1, list_dict_2):
    return [item for item in list_dict_1 if item not in list_dict_2]
        

CodePudding user response:

This method will work even if the lists are in a different order:

First of all, we need to do some processing to turn each dictionary into an immutable object. This is so we can add them to a set, which is an unsorted container that allows fast membership checking, along with other features.

processed_string1 = set((d["name"], d["age"]) for d in string1)
processed_string2 = set((d["name"], d["age"]) for d in string2)

Then we can use the set's difference method do get the items that are in the first set, but not the second:

result_set = processed_string1.difference(processed_string2)

Then we just have to convert back to a dictionary:

result_list = [{"name": t[0], "age": t[1]} for t in result_set]

CodePudding user response:

str1  = [i["name"] for i in string1]

get name in the string

str2  = [i["name"] for i in string2]

name not in string2 but in 1

not_in_string_2 = list(set(str1) ^ set(str2))

index of the value not in sring2

index = []
for x,i in enumerate(string1):
    if i["name"] in not_in_string_2:
        index.append(x)
for i in index:
   print(string1[i])

print the result

  • Related