1

i am trying to compare keys of different dictionaries stored in json.if keys are same then store those keys in another dictionary but i am not getting the required output. input looks like:

  [  
   {  
      "huma":10,
      "sana":25
   },
   {  
      "sara":12,
      "huma":20,
      "      zeb:15
   }
]

what i tried is:

def compare():
    result_dictionary = {}
    with open('data.json') as data_file:    
        data = json.load(data_file)
        for d1 in data:
            for key, value in d1.items():
                print("key: {key} | value: {value}".format(key=key, value=value))
compare()

i am confused how to compare these keys of multiple dictionaries and key which matches store them in a new dictionary? the output should be "Huma"because only that is equal in both dictionaries.

Nisarg
  • 1,631
  • 6
  • 19
  • 31
user3778289
  • 323
  • 4
  • 18
  • is your input data only 2 dictionaries? or maybe more ? what if there are 3 dictionaries, should your key be in all 3 before you store it in another dictionary ? what if there are 83 dictionaries, should the key be in all 83 ? or should the key be in a majority of dictionaries, or minority as long as it is >1 ? -- please update your question with more information... Also please show us your code on how you "store in a dictionary" or "compare keys", as your current code just does some printing. – Edwin van Mierlo May 23 '18 at 13:46
  • `import operator, functools` then `common_keys = functools.reduce(operator.and_, (d.keys() for d in data))` would produce a set of all common keys in a sequence of dictionaries. – Martijn Pieters May 23 '18 at 13:47
  • @EdwinvanMierlo it is not important that key should be in all dictionaries but if any of key match with any other key in a dictionary 1 or more time then it should be stored in another dictionary or in another list . right now i am just trying to get the common keys. – user3778289 May 23 '18 at 15:18
  • @user3778289 in that case you have a good answer already – Edwin van Mierlo May 23 '18 at 16:00

1 Answers1

3

Using collections

Demo:

import collections
d = [{  "huma":10,"sana":25}, { "sara":12,"huma":20,"zeb":15}]
dd = collections.defaultdict(list)
for i in d:
    for k,v in i.items():
        dd[k].append(v)
print([k for k,v in dd.items() if len(v) > 1])

Output:

['huma']
Rakesh
  • 81,458
  • 17
  • 76
  • 113