Reputation: 55
following is the dictionary of list's where list's have dictionary's
dict4 = {
234: [{'apple': 87}, {'fan': 88}, {'jackal': 89}],
345: [{'bat': 98}, {'car': 84}, {'ice': 80}],
456: [{'car': 86}, {'apple': 82}, {'goat': 80}],
567: [{'dog': 81}, {'cat': 80}, {'eagle': 90}],
678: [{'eagle': 98}, {'hawk': 89}, {'dog': 79}],
789: [{'fan': 89}, {'goat': 84}, {'car': 81}],
890: [{'hawk': 90}, {'ice': 85}, {'cat': 78}],
901: [{'goat': 85}, {'jackal': 90}, {'apple': 80}],
123: [{'ice': 87}, {'bat': 94}, {'bat': 92}],
546: [{'jackal': 91}, {'eagle': 93}, {'fan': 85}]
}
In the above dict4
, apple(as the sub-key) is present three times at different places i.e., ({'apple': 87},{'apple': 82}, {'apple': 80}
) , I would like to keep apple with highest value ({'apple': 87}
) , and omit the rest from dict4
and same applies to all other sub-keys.
Final output dict should look like
dict4 = {
234: [{'apple': 87}],
345: [{'bat': 98}],
456: [{'car': 86}],
567: [{'dog': 81}, {'cat': 80}],
678: [{'eagle': 98}],
789: [{'fan': 89}],
890: [{'hawk': 90}],
901: [{'goat': 85}],
123: [{'ice': 87}],
546: [{'jackal': 91}]
}
I can not think of way to approach the problem, any suggestions or help would be greatly appreciated
Thank you!
Upvotes: 0
Views: 73
Reputation: 11347
Iterate your structure and create a mapping sub-key => (super-key, value)
where value is the max among the same subkey:
maxes = {}
for main_key, ls in dict4.items():
for sub_key, val in ls[0].items():
if sub_key not in maxes or maxes[sub_key][1] < val:
maxes[sub_key] = (main_key, val)
print(maxes)
This creates a dict like
{'apple': (234, 87), 'bat': (345, 98), 'car': (456, 86), 'dog': (567, 81), 'eagle': (678, 98), 'fan': (789, 89), 'hawk': (890, 90), 'goat': (901, 85), 'ice': (123, 87), 'jackal': (546, 91)}
It should be easy to derive your desired structure from this.
Upvotes: 1
Reputation: 11
Try creating a dictionary to store the max value of each key.
temp
.key1
in dict4
, iterate over the list corresponding to key1
.temp
, save the key and the corresponding value in temp
. Else, store the larger value in temp
temp
, create new dict dict5
. Iterate over dict4
and for each key key1
in dict4
, only store the elements of the list which match both key and value in temp
dict5
Upvotes: 1