Comparing Python Dictionaries and Nested Dictionaries

Comparing Python dictionaries and nested dictionaries

comparing 2 dictionaries using recursion:

Edited for python 3 (works for python 2 as well):

d1= {'a':{'b':{'cs':10},'d':{'cs':20}}}
d2= {'a':{'b':{'cs':30} ,'d':{'cs':20}},'newa':{'q':{'cs':50}}}

def findDiff(d1, d2, path=""):
for k in d1:
if k in d2:
if type(d1[k]) is dict:
findDiff(d1[k],d2[k], "%s -> %s" % (path, k) if path else k)
if d1[k] != d2[k]:
result = [ "%s: " % path, " - %s : %s" % (k, d1[k]) , " + %s : %s" % (k, d2[k])]
print("\n".join(result))
else:
print ("%s%s as key not in d2\n" % ("%s: " % path if path else "", k))

print("comparing d1 to d2:")
findDiff(d1,d2)
print("comparing d2 to d1:")
findDiff(d2,d1)

Python 2 old answer:

def findDiff(d1, d2, path=""):
for k in d1:
if (k not in d2):
print (path, ":")
print (k + " as key not in d2", "\n")
else:
if type(d1[k]) is dict:
if path == "":
path = k
else:
path = path + "->" + k
findDiff(d1[k],d2[k], path)
else:
if d1[k] != d2[k]:
print (path, ":")
print (" - ", k," : ", d1[k])
print (" + ", k," : ", d2[k])

Output:

comparing d1 to d2:
a -> b:
- cs : 10
+ cs : 30
comparing d2 to d1:
a -> b:
- cs : 30
+ cs : 10

How to compare nested dicts

You can use recursion:

a_standard = {
'section1': {
'category1': 1,
'category2': 2
},
'section2': {
'category1': 1,
'category2': 2
}

}

a_new = {
'section1': {
'category1': 1,
'category2': 2
},
'section2': {
'category1': 1,
'category2': 3
}

}
def differences(a, b, section=None):
return [(c, d, g, section) if all(not isinstance(i, dict) for i in [d, g]) and d != g else None if all(not isinstance(i, dict) for i in [d, g]) and d == g else differences(d, g, c) for [c, d], [h, g] in zip(a.items(), b.items())]

n = filter(None, [i for b in differences(a_standard, a_new) for i in b])

Output:

[('category2', 2, 3, 'section2')]

Which yields the key corresponding to the unequal values.

Edit: without list comprehension:

def differences(a, b, section = None):
for [c, d], [h, g] in zip(a.items(), b.items()):
if not isinstance(d, dict) and not isinstance(g, dict):
if d != g:
yield (c, d, g, section)
else:
for i in differences(d, g, c):
for b in i:
yield b
print(list(differences(a_standard, a_new)))

Output:

['category2', 2, 3, 'section2']

This solution utilizes generators (hence the yield statement), which store the yielded values on the fly, only remembering where it left off. The values can be garnered by casting the returned result as a list. yield makes it easier to accumulate the value differences and removes the need to keep an additional parameter in the function or a global variable.

Compare keys and values of nested dictionaries in Python

The following should work and be significantly faster than yours:

from collections import defaultdict

diff_dict = defaultdict(dict)
for key, value in old_dictionary.items():
v = new_dictionary.get(key, None)
if v:
for key1, value1 in value.items():
v1 = v.get(key1, None)
if v1 and value1 != v1:
compared_value = str(value1) + '_' + str(v1)
diff_dict[key].update({key1: compared_value})

Also, FYI, proving a minimal example with input and desired output would really make the lives of those who want to help easier. Keep that in mind for next time.

I have created one myself:

old_dictionary = {'a': {'b': 1, 'c': 2}, 'd': {'f':5}}
new_dictionary = {'a': {'b': 2, 'c': 2}, 'd': {'f':6}}

which produces:

defaultdict(<class 'dict'>, {'a': {'b': '1_2'}, 'd': {'f': '5_6'}})

and if the defaultdict datatype at the end confuses you, you can always convert to a vanilla-dict simply by casting:

diff_dict = dict(diff_dict)

Comparing values from nested dictionaries in Python 3

a generator comprehension might help:

data = {
"a" : {'lod': '', 'p': '', 'm': '', 'b': '', 'xr': 0},
"b" : {'lod': '', 'p': '', 'm': '', 'b': '', 'xr': 1}
}

max_xr = max(value["xr"] for value in data.values())

print(max_xr)

That should give you 1 I think.

Comparing two dictionaries and checking how many (key, value) pairs are equal

If you want to know how many values match in both the dictionaries, you should have said that :)

Maybe something like this:

shared_items = {k: x[k] for k in x if k in y and x[k] == y[k]}
print(len(shared_items))

Comparing nested dictionaries into general dictionary

You can do it with itertools.combinations and a nested loop:

from itertools import combinations

for first_market, second_market in combinations(pricesDict, 2):
for produce in ["apples", "bananas", "melons"]:
first_price = pricesDict[first_market][produce]
second_price = pricesDict[second_market][produce]

if first_price != second_price:
print(
f"There is a price difference between {first_market}: {first_price} " +
f"and {second_market}: {second_price} in {produce}"
)

this prints:

There is a price difference between supermarket_1: 1 and supermarket_2: 1.5 in apples
There is a price difference between supermarket_1: 2 and supermarket_4: 2.7 in bananas
There is a price difference between supermarket_2: 1.5 and supermarket_3: 1 in apples
There is a price difference between supermarket_2: 1.5 and supermarket_4: 1 in apples
There is a price difference between supermarket_2: 2 and supermarket_4: 2.7 in bananas
There is a price difference between supermarket_3: 2 and supermarket_4: 2.7 in bananas

How to Use Loop for Nested Dictionaries to Compare Previous Values

I think that's pretty what you are looking for.

Here's my piece of code and it is intuitive. Here we may make use of Dict.keys() and we may later transform it as a list storing all the keys that can be referenced using any int variable like you tried to use. Later we put a try except block to catch any IndexError that will occur once when we reach at the and of the Dict

Dict = { 
"2020-03-27": {"Price": "483.4200", "Volume": "14377408"},
"2020-03-30": {"Price": "543.3600", "Volume": "14377408"},
"2020-04-01": {"Price": "613.1600", "Volume": "14377408"},
"2020-04-02": {"Price": "631.0900", "Volume": "14377408"}
}

for i in range(len(Dict)):
prev_key = list(Dict.keys())[i]

try:
next_key = list(Dict.keys())[i+1]

if float(Dict[next_key]['Price']) > float(Dict[prev_key]['Price']):
print("Higher Price than Previousday")

except:
print("Reached at The end !")

python nested dictionary comparison

I think there's just a small bug in your code, if you fix it, things will work as you expected

The line

type(new(key)) == dict

always fails as you should access the element of a dictionary with new[key]. You can replace the line if inside try with

if isinstance(new[key], dict)

By the way, it's never a good idea to make this kind of silent try except.



Related Topics



Leave a reply



Submit