VOOZH about

URL: https://www.geeksforgeeks.org/python/python-program-to-convert-dictionary-to-list-by-repeating-keys-corresponding-value-times/

⇱ Dictionary to List by Repeating keys corresponding value times - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Dictionary to List by Repeating keys corresponding value times - Python

Last Updated : 23 Jul, 2025

Given a dictionary where each key is a character and its corresponding value is a number, the task is to generate a list by repeating each keys character according to its value and if a character is repeated as a key in the dictionary then the value from its last occurrence will be considered. For example, If we have a dictionary d = {'g': 2, 'f': 3, 'g': 1, 'b': 4, 'e': 1, 's': 4, 't': 3} then output will be ['g', 'f', 'f', 'f', 'b', 'b', 'b', 'b', 'e', 's', 's', 's', 's', 't', 't', 't'].

Using loop and * operator

In this method we use a loop to iterate through dictionary items and repeats the key value times using the * operator.


Output
['g', 'f', 'f', 'f', 'b', 'b', 'b', 'b', 'e', 's', 's', 's', 's', 't', 't', 't']

Using List Comprehension

This method uses list comprehension to repeat each dictionary key according to its value, creating a flat list of repeated elements.


Output
['g', 'f', 'f', 'f', 'b', 'b', 'b', 'b', 'e', 's', 's', 's', 's', 't', 't', 't']

Explanation:

  • for k, v in d.items() retrieves the dictionary's keys and their values.
  • for _ in range(v) ensures each key is repeated exactly v times in the output list.

Using the collections module

This method leverages collections.Counter to handle the dictionary and repeat the elements and return them as a list using list().


Output
['g', 'f', 'f', 'f', 'b', 'b', 'b', 'b', 'e', 's', 's', 's', 's', 't', 't', 't']

Explanation:

  • collections.Counter(d) creates a Counter object from the dictionary d.
  • .elements() returns an iterator that yields the elements repeated by their counts, which is converted to a list using list().

Using the itertools module

This method uses itertools.repeat to repeat keys based on their values and itertools.chain to flatten the results into a single list.


Output
['g', 'f', 'f', 'f', 'b', 'b', 'b', 'b', 'e', 's', 's', 's', 's', 't', 't', 't']

Explanation:

  • itertools.repeat(k, v) repeats each key k v times.
  • itertools.chain.from_iterable() flattens the iterator of repeated keys into a single list.

Using reduce() from functools

In this method we use reduce() function to accumulate values by repeating the dictionary's key values.


Output
['g', 'f', 'f', 'f', 'b', 'b', 'b', 'b', 'e', 's', 's', 's', 's', 't', 't', 't']

Explanation: reduce() function accumulates results by applying the lambda function, which repeats the key val[0] for val[1] times.

Comment