Reputation: 47
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']
Upvotes: 4
Views: 180
Reputation: 1407
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。
Upvotes: 0
Reputation: 214949
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']
Upvotes: 5
Reputation: 208435
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]]
Upvotes: 0
Reputation: 78590
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']
Upvotes: 4