简体   繁体   中英

Adding elements from a list of lists into dictionary in Python

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?

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']

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)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM