Reputation: 25
I'm trying to combine a list, similar to the following
l = [['A', '1'], ['A', '2'], ['B', '1'], ['C', '1'], ['C', '2']]
into a dictionary, where the first element of a nested list is the key
d = {'A': ['1', '2'], 'B': ['1'], 'C': ['1', '2']}
Is it possible to do this fairly easily?
Upvotes: 1
Views: 1102
Reputation: 10624
You can use itertools.groupby:
l = [['A', '1'], ['A', '2'], ['B', '1'], ['C', '1'], ['C', '2']]
d={}
for i,k in itertools.groupby(sorted(l, key=lambda x: x[0]), key=lambda x: x[0]):
d[i]=list(itertools.chain(*(p[1:] for p in k)))
>>> print(d)
{'A': ['1', '2'], 'B': ['1'], 'C': ['1', '2']}
Upvotes: 1
Reputation: 73470
Simplest is the following, using dict.setdefault
:
d = {}
for k, v in l:
d.setdefault(k, []).append(v)
With a collections.defaultdict
, the code gets even cleaner:
from collections import defaultdict
d = defaultdict(list)
for k, v in l:
d[k].append(v)
Upvotes: 6
Reputation: 2311
Iterate over l and append in the keys of the dictionbary like this:
d = {}
for item in l:
if item[0] in d.keys():
d[item[0]].append(item[1])
if item[0] not in d.keys():
d[item[0]] = [item[1]]
Upvotes: 0
Reputation: 23815
Using defaultdict can help here
from collections import defaultdict
l = [['A', '1'], ['A', '2'], ['B', '1'], ['C', '1'], ['C', '2']]
d = defaultdict(list)
for x in l:
d[x[0]].append(x[1])
print(d)
output
defaultdict(<class 'list'>, {'A': ['1', '2'], 'B': ['1'], 'C': ['1', '2']})
Upvotes: 0
Reputation: 5531
Here is a traditional way of doing it. Just iterate over the list and append the keys and values to the dictionary. Here is the full code:
l = [['A', '1'], ['A', '2'], ['B', '1'], ['C', '1'], ['C', '2']]
dictionary = {}
for key,value in l:
if key in dictionary.keys():
dictionary[key].append(value)
else:
dictionary[key] = [value]
print(dictionary)
Output:
{'A': ['1', '2'], 'B': ['1'], 'C': ['1', '2']}
Upvotes: 0