I need your help to solve a problem.
I want to convert a dictionary d = {key1:value1, key2:value2}
into
list= [keys1, keys1, ... (value1 times), k
You can use a comprehension like below:
list(chain.from_iterable(map(int, ((str(k) + ',') * v).split(',')[:-1]) for k, v in d1.items()))
Code:
from itertools import chain
d1 = {4: 1, 3: 2, 12: 2}
print(list(chain.from_iterable(map(int, ((str(k) + ',') * v).split(',')[:-1]) for k, v in d1.items())))
# [4, 3, 3, 12, 12]
To avoid all those fancy splits and map
, you can go for:
[k for k, v in d1.items() for _ in range(v)]
which also outputs the desired output.