Dictionary Keys * values to a list in python

Viewed 90

My dict is as follows:

the_dict = {'1': 2,
 '2': 4,
 '3': 3,
 '8': 3,
 '9': 3,
 '10': 4,
 '14': 4}

I need to multiply the keys by the values to create a long flat list. My attempt is as follows but it screws up the 10 and 14:

new_target = []
for k, v in zip(the_dict.keys(), the_dict.values()):
    new_target += list(k*v)

This code produces: ['1', '1', '2', '2', '2', '2', '3', '3', '3', '8', '8', '8', '9', '9', '9', '1', '0', '1', '0', '1', '0', '1', '0', '1', '4', '1', '4', '1', '4', '1', '4']

That code comes close, but it doesn't work due to the following behavior on the 10 and 14; list("10" *2) produces ['1', '0', '1', '0'] instead of the desired ['10', '10'].

How do I create the desired list?

2 Answers

Adding onto M-Chen-3's answer, you can also condense it to something like this using list comprehension:

new_target = [k for k, v in the_dict.items() for _ in range(v)]

There are two changes you need to make to your code:

  1. Why iterate through zip(the_dict.keys(), the_dict.values()) when you can just iterate through the_dict.items() with the same results?

  2. Notice that if you enclose the string within a list, it doesn't matter how long the string is:

print(["10"]*2)
# Prints ['10', '10']
print(["1"]*2)
# Prints ['1', '1']

Also, as wim pointed out, the list function call is unnecessary as you are already creating a list.

With that said, below is the corrected code:

the_dict = {'1': 2,
 '2': 4,
 '3': 3,
 '8': 3,
 '9': 3,
 '10': 4,
 '14': 4}


new_target = []
for k, v in the_dict.items():
    new_target += [k]*v
    
print(new_target)
# Prints ['14', '14', '14', '14', '10', '10', '10', '10', '2', '2', '2', '2', '1', '1', 
# '3', '3', '3', '9', '9', '9', '8', '8', '8']

Check out diggy's answer for a shorter list comprehension version!

Related