Home > Back-end >  Convert numerical dictionary to list with duplicates in Python
Convert numerical dictionary to list with duplicates in Python

Time:10-05

A simple example:

What I have:

{10:1, 20:2, 30:3}

What I want:

[10, 20, 20, 30, 30, 30]

Any idea of compressed coding in Python 3 without using loops?

CodePudding user response:

"Compressed coding"? Maybe with a Counter from collections?

[*Counter(d).elements()]

Try it online!

CodePudding user response:

Nice use of a "dictionary comprehension" here:

freq_data = {10:1, 20:2, 30:3}
result = [category for (category,count) in freq_data.items() for iteration in range(count)]

# or succinctly
result = [k for k,v in freq_data.items() for _ in range(v)]

here what we do is expand the dictionary by the key,value pairs then iterate the key for the length of range(v)

CodePudding user response:

Two liner from my side:

dict_t = {10:1, 20:2, 30:3}
list_result = [v*[k] for k,v in dict_t.items()]
list_final = flatten(list_result)
print(list_final)

Using the flatten function provided at this link. flatten function

def flatten(t):
    return [item for sublist in t for item in sublist]

Result:

[10, 20, 20, 30, 30, 30]

CodePudding user response:

>>> dict_t = {10:1, 20:2, 30:3}
>>> print([i for s in [[k]*v for k,v in d.items()] for i in s])
[10, 20, 20, 30, 30, 30]
  • Related