I'm new to python and would really like to get some direction here.
I have two almost identical dictionaries - First_Dict and Second_Dict
First_Dict = {"Texas": ["San Antonio", "Austin", "Houston", "Dallas"],
"California": ["San Diego", "Los Angeles", "San Francisco"],
"Florida": ["Miami", "Orlando", "Jacksonville", "Naples"],
"Arizona": ["Phoenix", "Tucson"]}
Second_Dict = {"Texas": ["San Antonio, Austin, Houston"],
"California": ["San Diego, Los Angeles, San Francisco"],
"Florida": ["Miami", "Orlando", "Jacksonville"], "Illinois":
["Chicago", "Naperville"]}
Goal: I need to compare them in the following flow:
Compare keys
if key match
compare values
if all values match
break
else:
print the key and the corresponding missing value/s.
"Missing value/s on key "Florida" in the Second_Dict"
"Naples"
if keys NOT match or missing
print the unmatching/missing key and corresponding value/s.
"Missing key and value/s on First_Dict"
Illinois
Chicago
Naperville
"Missing key and value/s on Second_Dict"
Arizona
Phoenix
Tucson
My code isn't much so far :) Sorry, still learning.
for key, value in First_Dict.items() and Second_Dict.items():
if key in First_Dict.keys() == Second_Dict.keys():
for value in First_Dict.value() and Second_Dict.value :
if value in First_Dict.value() == Second_Dict.value():
break
else:
print(value)
I imagine that you want to know differences not only for the first dictionary from second, but also vice versa. For me a good way is to separate the control in the following steps:
Possible code:
#Step 1
#Determination of common keys
first_keys = first_Dict.keys() #retrieve keys of the dictionary
second_keys = second_Dict.keys()
common_keys = [key for key in first_keys if key in second_keys]
#Step 2
#so now for common keys we look for differences in value and printing them
for common in common_keys:
townsA = first_Dict[common]
townsB = second_Dict[common]
#with the first statement determine the cities that are in the second
#dictionary but not in first one.
#with the second the opposite
missingOnFirst = [town for town in townsB if town not in townsA]
missingOnSecond = [town for town in townsA if town not in townsB]
if missingOnFirst:
print("Missing on {0} in first dictionary: \n\t{1}".format(common,"\n\t".join(missingOnFirst)))
if missingOnSecond:
print("Missing on {0} in second dictionary: \n\t{1}".format(common,"\n\t".join(missingOnSecond)))
#Step 3
#printing the missing keys:
#on First dictionary
print("\n")
print("Missing key and value/s on first dictionary")
for key in second_keys:
if key not in common_keys:
print("{0}:\n\t{1}".format(key,"\n\t".join(second_Dict[key])))
#on Second dictionary
print("Missing key and value/s on second dictionary")
for key in first_keys:
if key not in common_keys:
print("{0}:\n\t{1}".format(key,"\n\t".join(first_Dict[key])))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments