Reputation: 3175
I have a list where it consists of a list inside a list. The inner list contains two items with inner_list[0] is an identifier/key and inner_list[1] is the corresponding value. I would like to put them into a dictionary where values that shares the same key will be appended to the same key.
An example:
list = [['Jan', 'Jim'], ['Feb', 'Maggie'], ['Jan', 'Chris'], ['Sept', 'Joey'],..['key', 'value']]
The outcome I was looking for:
Jan = ['Jim', 'Chris']
Feb = ['Maggie']
Sept = ['Joey']
Any ideas I can do this elegantly in Python?
Upvotes: 1
Views: 114
Reputation: 11
you could use setdefault
, so:
lis = [['Jan', 'Jim'], ['Feb', 'Maggie'], ['Jan', 'Chris'],
['Sept', 'Joey'], ['key', 'value']]
dic = {}
for key, val in lis:
dic.setdefault(key, []).append(val)
Upvotes: 0
Reputation: 250901
You can use collections.defaultdict
here:
>>> from collections import defaultdict
>>> lis = [['Jan', 'Jim'], ['Feb', 'Maggie'], ['Jan', 'Chris'], ['Sept', 'Joey'],['key', 'value']]
>>> dic = defaultdict(list)
>>> for k, v in lis:
... dic[k].append(v)
>>> dic['Jan']
['Jim', 'Chris']
>>> dic['Feb']
['Maggie']
>>> dic['Sept']
['Joey']
Upvotes: 6