Home > Mobile >  Dictionary of list's, where list's have dictionary's
Dictionary of list's, where list's have dictionary's

Time:10-05

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!

CodePudding user response:

Try creating a dictionary to store the max value of each key.

  1. Initialize an empty dict temp.
  2. Then for each key key1 in dict4, iterate over the list corresponding to key1.
  3. For each element in the list, if the key (for example apple) doesn't exist in temp, save the key and the corresponding value in temp. Else, store the larger value in temp
  4. Now that you have 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
  5. Return dict5

CodePudding user response:

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.

  • Related