countries1 = list(item['country'] for item in list1)
countries2 = list(item['country'] for item in list2)
compare1 = [country for country in countries1 if country not in countries2] # doesnt exist
compare2 = [country for country in countries1 if country in countries2] # exist
состояние дела:
state1 = list(item['state'] for item in list1)
state2 = list(item['state'] for item in list2)
compare1 = [state for state in state1 if state not in state2] # doesnt exist
ОБНОВЛЕННЫЙ КОД:
list1 = [{ 'country': 'brazil', 'state': 'oregon' , 'some_key': 'some _value'}, { 'country': 'japan', 'state': 'chicago'}, { 'country': 'australia', 'state': 'washington', 'water': 'clean'}, { 'country':'china', 'state':'Tokio'}]
list2 = [{ 'country': 'brazil', 'state': 'oregon'}, { 'country': 'america', 'state': 'new york'}, { 'country': 'australia', 'state': 'washington', 'water': 'clean'},{ 'country':'china'}]
def check_key(dict_key):
# Check if key exist in all dictionaries
for item in list1+list2:
if dict_key in item.keys():
status = True
else:
status = False
return status
return status
# If key exist in all dictionaries compare
# If key doesnt exist in all dictionaries skip to next key
for k in list1[0].keys():
# Ckeck if key exist in all dictionaries
status = check_key(k)
# test
#print ("key: {}, exist in all".format(k)) if status else print ("key: {}, doesn't exist in all".format(k)) # key: country, exist in all
if status: # True
# If key exist in all dictionaries
values1 = list(item[k] for item in list1)
values2 = list(item[k] for item in list2)
compare1 = [country for country in values1 if country not in values2] # doesnt exist
print ("For key: {}, values which doesnt exist in list2: {}".format(k,compare1))
compare2 = [country for country in countries1 if country in countries2] # exist
print("For key: {}, values which exist in list2: {}".format(k, compare2))
else: # False
# If key doesnt exist in all dictionaries
pass
Вывод:
For key: country, values which doesnt exist in list2: ['japan']
For key: country, values which exist in list2: ['brazil', 'australia', 'china']
ОБНОВЛЕННЫЙ КОД № 2 :):
list1 = [{ 'country': 'brazl', 'state': 'oregon'}, { 'country': 'japan', 'state': 'chicago'}, { 'country': 'australia', 'state': 'washington', 'water': 'clean'},{'country':'china'}]
for item in list1:
if 'state' in item.keys():
print (item['state'])
выход:
oregon
chicago
washington