Tim
Tim

Reputation: 87

Pythonic way to create a nested dictionary

I'm looking for a Pythonic way to create a nested dictionary from a list and dictionary. Both the statements below produce the same result:

a = [3, 4]
b = {'a': 1, 'b': 2}

c = dict(zip(b, a))
c = {k: v for k, v in zip(b, a)}

Output is:

{3: 'a', 4: 'b'}

The desired result is:

{3: {'a': 1}, 4: {'b': 2}}

I could start using loops, but I don't believe that is necessary. And off course, afterwards I will need to flatten those dictionaries again.

Upvotes: 4

Views: 382

Answers (3)

taleinat
taleinat

Reputation: 8701

In my opinion, a more "Pythonic" way would be to use more descriptive variable names, and the dict() constructor:

keys = [3, 4]
orig_dict = {'a': 1, 'b': 2}
nested_dict = {key: dict([item]) for (key, item) in zip(keys, orig_dict.items())}

And another approach, using an intermediate iterable:

sub_dicts = [dict([item]) for item in orig_dict.items()]
nested_dict = dict(zip(keys, sub_dicts))

Finally, just using loops seems just fine in this case:

nested_dict = {}
for key, item in zip(keys, orig_dict.items()):
    nested_dict[key] = dict([item])

Upvotes: -1

Red
Red

Reputation: 27557

Like this:

a = [3, 4]
b = {'a': 1, 'b': 2}
c = {i: {k:b[k]} for i,k in zip(a,b)}

print(c)

Output:

{3: {'a': 1}, 4: {'b': 2}}

Upvotes: 2

AKX
AKX

Reputation: 168913

>>> {k: {va: vb} for k, (va, vb) in zip(a, b.items())}
{3: {'a': 1}, 4: {'b': 2}}

Upvotes: 5

Related Questions