0

Im trying to compare the values of 2 Dictionaries and create a new dictionary containing keys of 1st dictionary with non matched values

D1 = {'ID1': ['Name'], 'ID2': ['Name', 'email', 'environment', 'team', 'product'], 'ID3': ['Name', 'team']}
D2 = {'SNO': ['Name', 'email', 'environment', 'team', 'product']}

I can take D2 as list also: D2 = ['Name', 'email', 'environment', 'team', 'product']

Expected result should be:

{'ID1': [ 'email', 'environment', 'team', 'product'], 'ID2': [], 'ID3': [ 'email', 'environment', 'product']}
DavideBrex
  • 2,374
  • 1
  • 10
  • 23
Sirisha M
  • 33
  • 4

3 Answers3

0

What you want is check if one of D2 is not in one of D1's arrays. This can be achieved with the following for loops:

D1 = {'ID1': ['Name'], 'ID2': ['Name', 'email', 'environment', 'team', 'product'], 'ID3': ['Name', 'team']}
D2 = {'SNO': ['Name', 'email', 'environment', 'team', 'product']}

diff = {'ID1': [], 'ID2': [], 'ID3': []} 
for i in D1:
    for j in D2['SNO']:
        if j not in D1[i]:
            diff[i].append(j)
print(diff)
ptrstr
  • 56
  • 3
0

You could do some easy dict-comprehension if there is no specific requirements:

D1 = {'ID1': ['Name'], 'ID2': ['Name', 'email', 'environment', 'team', 'product'], 'ID3': ['Name', 'team']}
D2 = {'SNO': ['Name', 'email', 'environment', 'team', 'product']}

print({i: list(set(D2['SNO'])-set(D1[i])) for i in D1})
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
  • Thank you so much. its working :) but may i know where you are appending into new dictionary? you are just printing – Sirisha M May 18 '20 at 12:28
  • @SirishaM Learn something about [dict-comprehension](https://stackoverflow.com/questions/14507591/python-dictionary-comprehension) and [list-comprehension](https://stackoverflow.com/questions/1747817/create-a-dictionary-with-list-comprehension) – jizhihaoSAMA May 18 '20 at 12:32
0

You should compare the values of each key from dict 1 D1 with values in value from dict D2. You could do it in 3 lines.

D1 = {'ID1': ['Name'], 'ID2': ['Name', 'email', 'environment', 'team', 'product'], 'ID3': ['Name', 'team']}
D2 = {'SNO': ['Name', 'email', 'environment', 'team', 'product']}

missing_values = {}
for k, v in D1.items():
    missing_values[k] = list(set(D2["SNO"]) - set(v))

print(missing_values)