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

前端 未结 5 514
醉梦人生
醉梦人生 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:05

    The easiest solution is to use collections.Counter. It features an elements() method that yields all elements with the correct count:

    >>> from collections import Counter
    >>> list(Counter(d1).elements())
    [4, 3, 3, 12, 12]
    

    If you want to implement this yourself, I think the most readable version is this for loop:

    from itertools import repeat
    
    result = []
    for k, count in d1.items():
        result += repeat(k, count)
    

提交回复
热议问题