How to convert a dictionary to a list by repeating the keys value times in Python

4 Answers

0 votes
import itertools
 
def dictionary_to_list(dictionary):
    result = list(itertools.chain.from_iterable(itertools.repeat(key, value) 
                  for key, value in dictionary.items()))
     
    return result
 
dictionary = {'aaa': 1, 'bbb': 2, 'ccc': 3}
 
lst = dictionary_to_list(dictionary)
print(lst)
 
 
 
'''
run:
 
['aaa', 'bbb', 'bbb', 'ccc', 'ccc', 'ccc']
 
'''

 



answered Feb 28 by avibootz
0 votes
def dictionary_to_list(dictionary):
    result = [k for k, v in dictionary.items() for _ in range(v)]

    return result

dictionary = {'aaa': 1, 'bbb': 2, 'ccc': 3}

lst = dictionary_to_list(dictionary)
print(lst)



'''
run:

['aaa', 'bbb', 'bbb', 'ccc', 'ccc', 'ccc']

'''

 



answered Feb 28 by avibootz
0 votes
from itertools import repeat 
 
def dictionary_to_list(dictionary):
    result = [x for k, v in dictionary.items() for x in repeat(k, v)]
     
    return result
 
dictionary = {'aaa': 1, 'bbb': 2, 'ccc': 3}
 
lst = dictionary_to_list(dictionary)
print(lst)
 
 
 
'''
run:
 
['aaa', 'bbb', 'bbb', 'ccc', 'ccc', 'ccc']
 
'''

 



answered Feb 28 by avibootz
0 votes
def dictionary_to_list(dictionary):
    result = []
    
    for k, v in dictionary.items():
        result.extend([k] * v)

    return result
 
dictionary = {'aaa': 1, 'bbb': 2, 'ccc': 3}
 
lst = dictionary_to_list(dictionary)
print(lst)
 
 
 
'''
run:
 
['aaa', 'bbb', 'bbb', 'ccc', 'ccc', 'ccc']
 
'''

 



answered Feb 28 by avibootz

Related questions

...