-2

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?

Zhili Qiao
  • 99
  • 1
  • 5

4 Answers4

4

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

[*Counter(d).elements()]

Try it online!

no comment
  • 6,381
  • 4
  • 12
  • 30
1

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)

Schalton
  • 2,867
  • 2
  • 32
  • 44
0

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]
bgorkhe
  • 321
  • 3
  • 13
0
>>> 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]
soumya-kole
  • 1,111
  • 7
  • 18