Daniel Daniel - 9 months ago 29
Python Question

How to turn a python dictionary into a list with intentionally duplicate values

I have a dictionary in the following form:

{'string1': 3, 'string2': 4, 'string3':2}


I want to turn it into a list with instances of the key as a function of its corresponding value pair. Like so:

['string1','string1','string1','string2','string2','string2','string2','string3','string3']


I am having an annoyingly difficult time figuring this out, as I feel there should be an elegant solution. Here's what I have so far:

t2 = [dictionary[key]*key for key in dictionary.keys()]


but that yields the following mess:

['string2string2string2string2', 'string3string3', 'string1string1string1']

Answer Source

You can try this, if the order of the keys is not important:

[k for k, v in d.items() for _ in range(v)]

#['string2',
# 'string2',
# 'string2',
# 'string2',
# 'string3',
# 'string3',
# 'string1',
# 'string1',
# 'string1']