Repeat dictionary values by their key in Python

Updated

Given a dictionary, repeat elements K times where K is key of dictionary.

Examples :

Input : test_dict = {4 : 5, 7 : 2, 9 : 6, 10 : 4}
Output :
{4: [5, 5, 5, 5], 7: [2, 2, 2, 2, 2, 2, 2], 9: [6, 6, 6, 6, 6, 6, 6, 6, 6], 10: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4]}
Explanation :
Each element is repeated by Key's value.

Input : test_dict = {4 : 5, 7 : 1, 9 : 3, 10 : 4}
Output :
{4: [5, 5, 5, 5], 7: [1, 1, 1, 1, 1, 1 ,1], 9: [3, 3, 3, 3, 3, 3, 3, 3, 3], 10: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4]}
Explanation :
Each element is repeated by Key's value.

Method #1 : Using loop + * operator

In this, we perform task of iterating each key and task of extending the number of elements  is done using * operator.

# Python3 code to demonstrate working of
# Extract values of Particular Key in Nested Values
# Using list comprehension

# initializing dictionary
test_dict = {4 : 5, 7 : 2, 9 : 6, 10 : 4}
             
# printing original dictionary
print("The original dictionary is : " + str(test_dict))

res = dict()
for ele in test_dict:
    
    # extending the value, keys number of times
    res[ele] = [test_dict[ele]] * ele

# printing result
print("The extended dictionary : " + str(res))
Output

The original dictionary is : {4: 5, 7: 2, 9: 6, 10: 4}
The extended dictionary : {4: [5, 5, 5, 5], 7: [2, 2, 2, 2, 2, 2, 2], 9: [6, 6, 6, 6, 6, 6, 6, 6, 6], 10: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4]}

Method #2 : Using dictionary comprehension + * operator

In this, task of iteration and assignment is done using dictionary comprehension to provide a 1 liner compact solution.

# Python3 code to demonstrate working of
# Extract values of Particular Key in Nested Values
# Using list comprehension

# initializing dictionary
test_dict = {4 : 5, 7 : 2, 9 : 6, 10 : 4}
             
# printing original dictionary
print("The original dictionary is : " + str(test_dict))

# one liner to solve problem
res = {ele : [test_dict[ele]] * ele for ele in test_dict}

# printing result
print("The extended dictionary : " + str(res))
Output

The original dictionary is : {4: 5, 7: 2, 9: 6, 10: 4}
The extended dictionary : {4: [5, 5, 5, 5], 7: [2, 2, 2, 2, 2, 2, 2], 9: [6, 6, 6, 6, 6, 6, 6, 6, 6], 10: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4]}
Comment
Next tutorial
Mithlesh Upadhyay Published 5 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials