Itamar Mushkin
Itamar Mushkin

Reputation: 2905

'flattening' a nested dictionary

I have a python dictionary where each value is another dictionary nested within (i.e. of the form (k: {_k: _v})).
I want to change it to a list (or set) of tuples of the form {(k,_k,_v)}.
For example:

dict_form = {'a': {'b': 5, 'c': 10},
             'b': {'c': 15,'d': 20}}

desired_output = {('a','b',5), ('a','c',10), ('b','c',15), ('b','d',20)}

I'm looking for the pythonic, concise way to do it.
Thanks in advance!

edited: my solution was
set.union(*({(k,_k,_v) for _k, _v in v.items()} for k,v in dict_form.items()))
but the accepted answer is more concise (even if they are equivalent)

Upvotes: 1

Views: 29

Answers (1)

Rakesh
Rakesh

Reputation: 82765

Using a nested set comprehension

Ex:

dict_form = {'a': {'b': 5, 'c': 10},
             'b': {'c': 15,'d': 20}}
print({(k, m, n) for k, v in dict_form.items() for m, n in v.items()})

Output:

{('a', 'b', 5), ('b', 'c', 15), ('b', 'd', 20), ('a', 'c', 10)}

Upvotes: 1

Related Questions