I have a dictionary of this kind, {3:[1,2,3,4],4:[1,2,3,5,6,8,9]......}
with n key,value pairs. This dictionary will have key and values added for 'm' number of iterations,{3:[1,2,3,4],4:[1,2,3,5,6,8,9,10],5:[4,5,6,8]
. Here for the key '4' there is a new value in the list which is 10 but the key '3' does not have any value that has changed. So the output has to return there is no change for value in '3' after the next iteration. How can I solve this problem?
Asked
Active
Viewed 46 times
-1

Aqua 4
- 771
- 2
- 9
- 26

Sidharth Sekhar
- 11
- 2
-
1Duplicate of https://stackoverflow.com/questions/4527942/comparing-two-dictionaries-and-checking-how-many-key-value-pairs-are-equal – Luv May 04 '20 at 05:48
2 Answers
0
I'm assuming you are not concerned about the order of integers. Thus you are looking for a set comparison.
orig_d = {3: [1, 2, 3, 4], 4: [1, 2, 3, 5, 6, 8, 9]}
m = 1
for i in range(m):
new_d = {3: [1, 2, 3, 4], 4: [1, 2, 3, 5, 6, 8, 9, 10], 5: [4, 5, 6, 8]}
for k, v in new_d.items():
if set(v) - set(orig_d.get(k, [])):
orig_d[k] = v
print('Change in', k)
else:
print('No change in', k)
#Output
No change in 3
Change in 4
Change in 5
A set comparison works by comparing the unique values in one list with the unique values in another list.
The subtraction means, are there values present in the new list, that are not present (or do not get subtracted) by the original list.

Abhishek J
- 2,386
- 2
- 21
- 22
0
You can copy this dictionary in another dictionary and then change the other one. You can try this code. Hope this helps
dict1 = {3:[1,2,3,4],4:[1,2,3,5,6,8,9]}
dict2 = {3:[1,2,3,4],4:[1,2,3,5,6,8,9]}
x = 0
y = 10
while x < 4:
dict1[4].append(y)
x += 1
y += 1
if bool(set(dict1[3]) - set(dict2[3])) == False:
print('No change')

Arsh Kenia
- 123
- 1
- 7