I need to convert a Dictionary to a List where the key is repeated the number of times of the value.
dict = {'foo':3, 'bar':1}
expect result:
['foo', 'foo', 'foo', 'bar']
I need to convert a Dictionary to a List where the key is repeated the number of times of the value.
dict = {'foo':3, 'bar':1}
expect result:
['foo', 'foo', 'foo', 'bar']
Using collections.Counter
:
>>> [*Counter(dict).elements()]
['foo', 'foo', 'foo', 'bar']
A little benchmark comparing this with a supposedly faster solution (and a third solution, doing what Counter
does, but directly to the dict). Numbers are times, so lower=faster:
0.31 Counter
0.70 listcomp
0.27 itertools
0.32 Counter
0.72 listcomp
0.28 itertools
0.32 Counter
0.72 listcomp
0.29 itertools
Benchmark code:
import timeit
from collections import Counter
from itertools import chain, starmap, repeat
data = {i: i % 10 + 1 for i in range(1000)}
solutions = {
'Counter': lambda: [*Counter(data).elements()],
'listcomp': lambda: [v for v, c in data.items() for _ in range(c)],
'itertools': lambda: list(chain.from_iterable(starmap(repeat, data.items())))
}
for _ in range(3):
for name, solution in solutions.items():
t = min(timeit.repeat(solution, number=1000))
print('%.2f' % t, name)
print()
Use a list comprehension to create a sub lists of required length and then flatten it:
list(chain.from_iterable([[k] * v for k, v in dict.items()]))
Example:
from itertools import chain
dict = {'foo':3, 'bar':1}
print(list(chain.from_iterable([[k] * v for k, v in dict.items()])))
# ['foo', 'foo', 'foo', 'bar']
you can use simple list comprehension to complete the job.
mylist = [key for key, value in mydict.items() for _ in range(value)]
Output:
['foo', 'foo', 'foo', 'bar']
Try this:
dict = {'foo':3, 'bar':1}
my_list = []
for key, value in dict.items():
for _ in range(value):
my_list.append(key)
Output:
['foo', 'foo', 'foo', 'bar']
if __name__ == '__main__':
result = []
dict = {'foo': 3, 'bar': 1}
for key in dict.keys():
key_value = dict[key]
for i in range(key_value):
result.append(key)
print(result)
or you could do:
if __name__ == '__main__':
result = []
dict = {'foo': 3, 'bar': 1}
result = [k for k, v in dict.items() for _ in range(v)]
print(result)
Both Outputs are:
['foo', 'foo', 'foo', 'bar']
Here is a simple way using plain list comprehension coupled with list multiplication.
d = {'foo':3, 'bar':1}
l = [item for k,v in d.items() for item in [k]*v]
print(l)
['foo', 'foo', 'foo', 'bar']