How to convert a dictionary to a list of keys, with repeat counts given by the values?

前端 未结 5 525
醉梦人生
醉梦人生 2020-12-10 09:47

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

5条回答
  •  没有蜡笔的小新
    2020-12-10 10:07

    d1={4:1,3:2,12:2} 
    ans =[]
    for key,value in d1.items():
        ans.append((str(key),)*value)
    print(ans)
    flattened = []
    list(flattened.extend(item) for item in ans)
    print(flattened)
    

    Output:

    [('4',), ('3', '3'), ('12', '12')]
    ['4', '3', '3', '12', '12']
    

提交回复
热议问题