'Finding the difference in value counts by keys in two Dictionaries
I have two sample python dictionaries that counts how many times each key appears in a DataFrame.
dict1 = {
2000 : 2,
3000 : 3,
4000 : 4,
5000 : 6,
6000 : 8
}
dict2 = {
4000 : 4,
3000 : 3,
2000 : 4,
6000 : 10,
5000 : 4
}
I would like to output the following where there is a difference.
diff = {
2000 : 2
5000 : 2
6000 : 2
}
I would appreciate any help as I am not familiar with iterating though dictionaries. Even if the output shows me at which key there is a difference in values, it would work for me. I did the following but it does not produce any output.
for (k,v), (k2,v2) in zip(dict1.items(), dict2.items()):
if k == k2:
if v == v2:
pass
else:
print('value is different at k')
Solution 1:[1]
Since you're counting... how about using Counters?
c1, c2 = Counter(dict2), Counter(dict1)
diff = dict((c1-c2) + (c2-c1))
If you used Counters all around, you wouldn't need the conversions from dict and back. And maybe it would also simplify the creation of your two count dicts (Can't tell for sure since you didn't show how you created them).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kelly Bundy |
