Generate a list from the keys of a dictionary taking into account the values of these keys

0

For example if you have the following dictionary:

{1:2, 2:3}

I want to get the following list:

[1, 1, 2, 2, 2]

That is: there are as many "1" as values indicates the value of the key "1" (2) and as many "2" as values indicates the value of the key "2" (3).

    
asked by Felka98 04.07.2018 в 03:44
source

1 answer

1

One way could be the following:

d = {1:2,2:3}

l=[]
map(l.extend, ([k]*d[k] for k in d))
print(l)

[1, 1, 2, 2, 2]

([k]*d[k] for k in d) is a generating expression that generates a set of lists, each one has the value of each key of the dictionary repeated by the value of said key, that is to say: [[1, 1], [2, 2, 2]] . Transforming this into a flat list is as simple as applying to each sublist the extend of an empty list.

    
answered by 04.07.2018 в 05:23