简体   繁体   中英

python dictionary to duplicated list

How do you convert a dictionary to a duplicated list in python?

For example: {'a':1,'b':2,'c':1,'d':3} to ['a','b','b','c','d','d','d']

Counter.elements from the collections module does exactly that:

d = {'a':1,'b':2,'c':1,'d':3}
from collections import Counter
print sorted(Counter(d).elements())
# ['a', 'b', 'b', 'c', 'd', 'd', 'd']

You can do this as a nested list comprehension:

d = {'a':1,'b':2,'c':1,'d':3}
d2 = [k for k, v in d.items() for _ in range(v)]
# ['a', 'c', 'b', 'b', 'd', 'd', 'd']

However, note that the order will be arbitrary (since dictionary keys have no ordering). If you wanted it to be alphabetical order, do

d2 = [k for k, v in sorted(d.items()) for _ in range(v)]
# ['a', 'b', 'b', 'c', 'd', 'd', 'd']
d = {'a':1,'b':2,'c':1,'d':3}
result = [x for k, v in d.items() for x in k * v]

Or if you want to ensure a sorted order:

d = {'a':1,'b':2,'c':1,'d':3}
result = [x for k in sorted(d) for x in k * d[k]]

Use itertools.repeat is faster. If D={'a':1,'b':2,'c':1,'d':3}, result=['a','b','b','c','d','d','d'] .

from itertools import repeat
result=reduce(lambda la,lb:la+lb,[list(itertools.repeat(k,v)) for k,v in D.items()],[])

A much clear way,

from itertools import repeat
result=[]
for k,v in D.items():
    result+=list(repeat(k,v))

ps.

假设你用的OrderedDict。稍微解释一下第一种。reduce有三个参数,目标是把你字典产生的list,通过最后一个初始值[],来不断reduce为一个结果list。“你字典产生的list” 就是通过items()生成的(key,value)这种pair的list。

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