IUnknown
IUnknown

Reputation: 9809

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'..},
  'B':{'B1':'B1V','B2':'B2V'...},
  ...}

Expected output:

['A1V','A2V','B1V','B2V'...]

Upvotes: 2

Views: 907

Answers (3)

MSeifert
MSeifert

Reputation: 152647

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'}

Upvotes: 5

Harry
Harry

Reputation: 318

dictionary = { 'A':{'A1':'A1V','B2':'A2V'},'B':{'B1':'B1V','B2':'B2V'}}

for key in dictionary.keys() :
    dict1 = dictionary[key]
    for key1 in dict1.keys():
        print(dict1[key1])

Tried to keep it as simple as possible.

Upvotes: 0

gyani
gyani

Reputation: 21

uniques = set()
for ukey, uvalue in outerdic.items():
    for lkey, lvalue in uvalue.items():
        uniques.add(lvalue)
print uniques

Using a set should work. New to stackoverflow, trying to figure out how syntax highlighting works.

This assumes that the dictionary is called outerdic.

Upvotes: 0

Related Questions