Comparing dictionaries with fewer loops

  • A+

I have a dictionary which has dictionaries as its values. Following is the structure of my dictionary

myD = {'key1': {'x' : 123, 'y' : 432},        'key2': {'x' : 456, 'y' : 565},        'key2': {'x' : 789, 'y' : 420},        ..........} 

I need to compare the values of this dictionary ( as you can see I have similar dictionary structure in each value) and generate following output. Strategy is going through every dictionary in value field and select the minimum value for a given key and insert it into a new dictionary. As an example if we consider x key from the value dictionaries, it has 123 as the minimum. So my new dictionary should have x:123.

my_newD =  {'x' : 123, 'y' : 420, ....} 

I can use 3 for loops to implement this, but is there any elegant way to do this with fewer for loops?


Here's an O(n) solution using collections.defaultdict:

from collections import defaultdict  myD = {'key1': {'x' : 123, 'y' : 432},        'key2': {'x' : 456, 'y' : 565},        'key3': {'x' : 789, 'y' : 420}}  # initialise defaultdict of lists d = defaultdict(list)  # iterate input dictionary and add values to lists for v1 in myD.values():     for k2, v2 in v1.items():         d[k2].append(v2)  # calculate minimum res = {k: min(v) for k, v in d.items()}  print(res)  {'x': 123, 'y': 420} 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: