IUnknown IUnknown - 4 years ago 114
Python Question

Processing dictionary of dictionaries

I have a dictionary - where the values are dictionaries themselves.

How do I extract the unique set of the values from the child dictionaries in the most efficient way?

{ 'A':{'A1':'A1V','B2':'A2V'..},

Expected output:


Answer Source

In a single line:

>>> [val for dct in x.values() for val in dct.values()]
['A1V', 'A2V', 'B2V', 'B1V']

Assuming you named your dict of dict x.

You mentioned unique, in that case replace the list-comprehension by a set-comprehension:

>>> {val for dct in x.values() for val in dct.values()}  # curly braces!
{'A1V', 'A2V', 'B1V', 'B2V'}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download