Search code examples
pythonlistdictionarycounting

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


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), keys2, ... (value2 times)] without using a nested loop.

Example:

d1 = {4: 1, 3: 2, 12: 2}

The code should produce the output:

l = [4, 3, 3, 12, 12]

This is what I have:

for key, value in nums1.items():
        temp = (str(key))*value
        nums2.append(int(temp))
print(nums2)

Which gives: [4, 33, 1212], but should give [4, 3, 3, 12, 12].

The complexity should be O(n).


Solution

  • 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)