У меня есть программа, которая сравнивает два питона dicts, и она отлично работает для не вложенных словарей с глубиной 1. Алгоритма довольно прост:Python вложенного ДИКТ сравнить алгоритм
for key in dict1, if not in dict2
print "-" key
for key in dict2, if not in dict1
print "+" key
for dict2Value, if not equal to dict1Value
print "+" dict2value
print "-" dict1value
Как я это сказал отлично работает с dicts, которые имеют глубину 1 и не вложены. Как изменить алгоритм работы с вложенными и dicts с большей глубиной, я застрял на некоторое время.
мой код:
def print_diff(dict1, dict2):
for n in dict1:
if n not in dict2:
print('- "' + str(n) + '":')
for n in dict2:
if n not in dict1:
print('+ "' + str(n) + '":')
continue
if dict2[n] != dict1[n]:
if type(dict2[n]) not in (dict, list):
print('- "' + str(n) + '" : "' + str(dict1[n]))
print('+ "' + str(n) + '" : "' + str(dict2[n]))
else:
if type(dict2[n]) == dict:
print_diff(dict1[n], dict2[n])
continue
return
Какой код вы пробовали ? – Totem
Каков ожидаемый результат для 'dict1 = {'a': 3, 'b': {'b': 4, 'a': 5}}' и 'dict2 = {'a': {'a': 3, 'b': 4}, 'a': 5} '? – Hyperboreus
@Totem добавил мой код к основному сообщению – user3230554