Dictionary to List by Repeating keys corresponding value times - Python
Last Updated :
28 Jan, 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.
Python
d = {'g': 2, 'f': 3, 'g': 1, 'b': 4, 'e': 1, 's': 4, 't': 3}
res = []
for k, v in d.items():
res += [k] * v
print(res)
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.
Python
d = {'g': 2, 'f': 3, 'g': 1, 'b': 4, 'e': 1, 's': 4, 't': 3}
# list comprehension repeat key `v` times
res = [k for k, v in d.items() for _ in range(v)]
print(res)
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().
Python
import collections
d = {'g': 2, 'f': 3, 'g': 1, 'b': 4, 'e': 1, 's': 4, 't': 3}
# using collections.Counter to flatten dictionary into a list
res = list(collections.Counter(d).elements())
print(res)
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().
This method uses itertools.repeat to repeat keys based on their values and itertools.chain to flatten the results into a single list.
Python
import itertools
d = {'g': 2, 'f': 3, 'g': 1, 'b': 4, 'e': 1, 's': 4, 't': 3}
# using itertools to repeat keys according to their values
res = list(itertools.chain.from_iterable(itertools.repeat(k, v) for k, v in d.items()))
print(res)
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.
In this method we use reduce() function to accumulate values by repeating the dictionary's key values.
Python
from functools import reduce
d = {'g': 2, 'f': 3, 'g': 1, 'b': 4, 'e': 1, 's': 4, 't': 3}
# using reduce to construct the list
res = reduce(lambda lst, val: lst + [val[0]] * val[1], d.items(), [])
print(res)
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.
Similar Reads
Python - Convert key-values list to flat dictionary We are given a list that contains tuples with the pairs of key and values we need to convert that list into a flat dictionary. For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age':
3 min read
Create a List using Custom Key-Value Pair of a Dictionary - Python The task of creating a list using custom key-value pairs from a dictionary involves extracting the dictionaryâs keys and values and organizing them into a list of tuples. This allows for the flexibility of representing data in a sequence that maintains the relationship between keys and values.For ex
3 min read
Python - Rearrange dictionary for consecutive value-keys Sometimes, while working with Python dictionaries, we can have a problem in which we need to rearrange dictionary keys so as a value is followed by same key in dictionary. This problem can have application in competitive programming algorithms and Graph problems. Let's discuss certain ways in which
4 min read
Convert Dictionary Value list to Dictionary List Python Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in whi
9 min read
Convert List of Tuples to Dictionary Value Lists - Python The task is to convert a list of tuples into a dictionary where the first element of each tuple serves as the key and the second element becomes the value. If a key appears multiple times in the list, its values should be grouped together in a list.For example, given the list li = [(1, 'gfg'), (1, '
4 min read
Get Python Dictionary Values as List - Python We are given a dictionary where the values are lists and our task is to retrieve all the values as a single flattened list. For example, given the dictionary: d = {"a": [1, 2], "b": [3, 4], "c": [5]} the expected output is: [1, 2, 3, 4, 5]Using itertools.chain()itertools.chain() function efficiently
2 min read