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))
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))