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.
>>> {k: {va: vb} for k, (va, vb) in zip(a, b.items())}
{3: {'a': 1}, 4: {'b': 2}}
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}}
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])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.