简体   繁体   中英

Python Compare two specific dictionaries

I want to compare two specific dictionaries :

dict1 = {"person1": {
      "name": "toto",
      "age": 24
    }, 
    "person2": {
      "name": "titi",
      "age": 24}
    }

dict2 = {"person2": {
      "name": "tata",
      "age": 22
    }, 
    "person3": {
      "name": "tete",
      "age": 25}
    }

I want to compare the difference between : - person1,person2 (dict1) and person2, person3 (dict2) - if the person2 is the same, and to compare name and age if it is the same or not

I already compare the first key, but the second key value not.

The dict1 is the true dictionnary :

def not_matches(dict_one, dict_two):
    dict_one = set(dict_one)
    dict_two = set(dict_two)
    ldel, ladd = list(dict_two - dict_one), list(dict_one - dict_two)
    return ldel, ladd

list_delete = list()
list_add = list()

list_delete, list_add = not_matches(dict1, dict2)
print(list_delete)
print(list_add)

['person3']
['person1']

Try this way:

for k1, v1 in dict1.items():
  v2 = dict2.get(k1, None)
  if v2:
    print(k1, '---- found:')
    print(v1['name'], v2['name'])
    print(v1['age'], v2['age'])

Add customisation for comparing the nested keys.


To compare the main keys, the class set comes in hand:

 keys1 = set(dict1.keys()) keys2 = set(dict2.keys()) print(keys1 - keys2) #=> {'person1'} print(keys2 - keys1) #=> {'person3'} print(keys1 & keys2) #=> {'person2'}

So the above code could be changed into:

 for k in keys2 & keys1: d1, d2 = dict1[k], dict2[k] print ( (d1['name'] == d2['name']) & (d1['age'] == d2['age']))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM