-4

I have a dd object:

dd = {'111': {'10': {'cid': '555', 'num': '0'}}, '222': {'10': {'cid': '555', 'num': '2'}}, '333': {'10': {'cid': '555', 'num': '2'}}, '121': {'10': {'cid': '555', 'num': '4'}}}

with similar cid.

I need to find the max dd object with num:

desired:

desired: {'121': {'10': {'cid': '555', 'num': '4'}}}

I know how to iterate over a nested dict to find the max key

 print(max(int(z['num']) for d in dd.values() for z in d.values()))  # 4

^ but this gives the value of num and not the complete object

Jack Jee
  • 1
  • 2

1 Answers1

0

Below

dd = {'111': {'10': {'cid': '555', 'num': '0'}}, '222': {'10': {'cid': '555', 'num': '2'}},
      '333': {'10': {'cid': '555', 'num': '2'}}, '121': {'10': {'cid': '555', 'num': '4'}}}

pair = max([(int(v['num']), val, key) for key, val in dd.items() for v in val.values()], key=lambda item: item[0])
print({pair[2]: pair[1]})

output

{'121': {'10': {'cid': '555', 'num': '4'}}}
balderman
  • 22,927
  • 7
  • 34
  • 52
  • Changing the `dict` object position, gives the incorrect result. For example on this input data `dd = {'111': {'10': {'cid': '555', 'num': '4'}}, '222': {'10': {'cid': '555', 'num': '2'}}, '333': {'10': {'cid': '555', 'num': '2'}}, '444': {'10': {'cid': '555', 'num': '3'}}}` it gives incorrect result – Jack Jee Oct 11 '20 at 11:39
  • @JackJee I have tested the code using your `dd` and got the expected result: `{'10': {'cid': '555', 'num': '3'}}` – balderman Oct 11 '20 at 11:44
  • yes, and that is incorrect. see there is a `num:4` present in the `dd` – Jack Jee Oct 11 '20 at 11:45
  • @JackJee Bug was solved. However the code is not very nice.. – balderman Oct 11 '20 at 12:10