Reputation: 327
I have a dictionary with multiple values follows:
dict_a = {1: {'a':1, 'b':2, 'c':3}, 2:{'a': 4, 'b':5, c:'6'}}
.
I want the result as such:
[('a',(1,4)),('b',(2,5)), ('c',(3,6))]
I wrote a code:
for keys, values in dict_a:
for k, v in values:
print(v)
But the result comes like ('a',1),('b',2)
....
I am little stuck here. Can anyone help me on this please!!!
Upvotes: 2
Views: 1902
Reputation: 164783
You can use a list comprehension:
dict_a = {1: {'a':1, 'b':2, 'c':3}, 2: {'a':4, 'b':5, 'c':6}}
res = [(k, tuple(d[k] for d in dict_a.values())) for k in dict_a[1]]
[('a', (1, 4)), ('b', (2, 5)), ('c', (3, 6))]
Assumes:
dict_a
is ordered by outer key, which may be automatic in Python 3.6+. Otherwise, use collections.OrderedDict
.dict_a
are the same.Upvotes: 3
Reputation: 51165
Using a collections.defaultdict
:
Setup
from collections import defaultdict
dct = defaultdict(tuple)
for _, v in dict_a.items():
for el in v:
dct[el] += (v[el],)
print(list(dct.items())
[('a', (1, 4)), ('b', (2, 5)), ('c', (3, '6'))]
Upvotes: 1