简体   繁体   中英

How create a dict from a specific python list

I have a python list:

[('Three', 8), ('Nine', 9), ('Two', 4), ('Two', 5), ('One', 0), ('One', 1), ('One', 6)]

and I want to create a python dictionary:

{ 'One', [0,1,6], 'Two':[4,5], 'Three':[8], 'Nine':[9] }

How can I do this with a list comprehension? I tried to create lists with numbers which belong to the same string value, but I do not know how to create a list on-the-fly in a list comprehension.

Just use a regular for loop:

from collections import defaultdict

d = defaultdict(list)

for key, value in your_list:
    d[key].append(value)

I would use defaultdict but if you really want to play with comprehension you can try

{k : [v for kk, v in l if k == kk] for k in set(i for i, _ in l)}
{'Nine': [9], 'One': [0, 1, 6], 'Three': [8], 'Two': [4, 5]}

I would not recommend it, for efficiency and readability reason.

>>> from operator import itemgetter as get
>>> from itertools import groupby as gb
>>> l = [('Three', 8), ('Nine', 9), ('Two', 4), ('Two', 5), ('One', 0), ('One', 1), ('One', 6)]

>>> {k: zip(*list(v))[1] for k,v in gb(sorted(l), get(0))}
{'Two': (4, 5), 'Nine': (9,), 'Three': (8,), 'One': (0, 1, 6)}

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