I have a dictionary
JavaScript
x
2
1
d = {1: 3, 5: 6, 10: 2}
2
I want to convert it to a list that holds the keys of the dictionary. Each key should be repeated as many times as its associated value.
I’ve written this code that does the job:
JavaScript
1
8
1
d = {1: 3, 5: 6, 10: 2}
2
l = []
3
for i in d:
4
for j in range(d[i]):
5
l.append(i)
6
l.sort()
7
print(l)
8
Output:
JavaScript
1
2
1
[1, 1, 1, 5, 5, 5, 5, 5, 5, 10, 10]
2
But I would like it to be a list comprehension. How can this be done?
Advertisement
Answer
You can do it using a list comprehension:
JavaScript
1
2
1
[i for i in d for j in range(d[i])]
2
yields:
JavaScript
1
2
1
[1, 1, 1, 10, 10, 5, 5, 5, 5, 5, 5]
2
You can sort it again to get the list you were looking for.