Reputation: 41
I have a Python list which holds key/values
[ [001, 'A', '100'], [001, 'B', '94'], [002, 'A', '87'], [002, 'B', '85'] ]
but the first 2 columns make a unique key. I want to convert the list into a dictionary, where multiple values per key would be aggregated into a dictionary of dictionaries for easy value lookups
{'001': {'A':'100','B':'94'}, '002': {'A':'87','B':'85'} }
What would be the elegant Python way of doing this? Thanks.
Upvotes: 2
Views: 1497
Reputation: 5660
In a dictionary comprehension:
>>> l = [ ['001', 'A', '100'], ['001', 'B', '94'], ['002', 'A', '87'], ['002', 'B', '85'] ]
>>> {l[i][0]:{k:v for (k, v) in zip(l[i][1:], l[i+1][1:])} for i in range(0, len(l), 2)}
{'002': {'A': 'B', '87': '85'}, '001': {'100': '94', 'A': 'B'}}
Upvotes: 0
Reputation: 152647
Probably the best way is a defaultdict using a dict as factory:
from collections import defaultdict
dictofdicts = defaultdict(dict)
start = [ ['001', 'A', '100'], ['001', 'B', '94'], ['002', 'A', '87'], ['002', 'B', '85'] ]
for outerkey, innerkey, value in start:
dictofdicts[outerkey][innerkey] = value
and this gives you the solution you wanted:
>>> dictofdicts
defaultdict(dict,
{'001': {'A': '100', 'B': '94'}, '002': {'A': '87', 'B': '85'}})
The defaultdict can be used like a normal dictionary but you can also convert it to a plain dictionary afterwards:
>>> dict(dictofdicts)
{'001': {'A': '100', 'B': '94'}, '002': {'A': '87', 'B': '85'}}
Upvotes: 2
Reputation: 107287
You can use collections.defaultdict()
:
In [54]: lst = [ ['001', 'A', '100'], ['001', 'B', '94'], ['002', 'A', '87'], ['002', 'B', '85'] ]
In [55]: from collections import defaultdict
In [56]: d = defaultdict(dict)
In [57]: for i, j, k in lst:
....: d[i].update({j:k})
....:
In [58]: d
Out[58]: defaultdict(<class 'dict'>, {'001': {'A': '100', 'B': '94'}, '002': {'A': '87', 'B': '85'}})
Upvotes: 2