Reputation: 363
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']
Upvotes: 2
Views: 65
Reputation: 5075
The only thing you messed up was you forgot to put key in square brackets, here:
dictionary = {'string1': 3, 'string2': 4, 'string3':2}
t2 = [dictionary[key]*[key] for key in dictionary.keys()]
print(t2)
result:
[['string2', 'string2', 'string2', 'string2'], ['string1', 'string1', 'string1'], ['string3', 'string3']]
* EDIT *
If you want a flattened version here's the modified code for that:
t2 = [''.join(j) for j in [[i]for arr in [dictionary[key]*[key] for key in dictionary.keys()] for i in arr]]
result:
['string3', 'string3', 'string2', 'string2', 'string2', 'string2', 'string1', 'string1', 'string1']
Upvotes: 1
Reputation: 30258
You can use collections.Counter()
to do this:
>>> list(Counter(d).elements())
['string1', 'string1', 'string1', 'string3', 'string3', 'string2', 'string2', 'string2', 'string2']
Of course with a dictionary, order is not guaranteed.
Upvotes: 4
Reputation: 214927
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']
Upvotes: 5