Change language

Python | Loop through a dictionary of lists of values

| | |

Method # 1: Using List Comprehension
List Comprehension can be used to accomplish this particular task. It’s just shorthand for normal nested loops. we iterate over each list of keys and store the result.

# Python3 code to demonstrate how it works
# Looping through a dictionary of lists of values ​​
# Using an understanding list

 
# Initialize dictionary

test_dict = { ’gfg’ : [ 1 , 2 ], ’is’ : [ 4 , 5 ], ’best’ : [ 7 , 8 ]}

 
# print the original dictionary

print ( "The original dictionary : " +   str (test_dict))

 
# Using the comprehension list
# Loop through a dictionary of lists of values ​​

res = [[i for i in test_dict [x]] for x in test_dict.keys ()]

 
# print result

print ( "The list values ​​of keys are: " + str (res))

Output:

The original dictionary: {’best’: [7, 8], ’is’: [4, 5], ’gfg’: [1, 2]}
The list values ​​of keys are: [[7, 8] , [4, 5], [1, 2]]

Method # 2: Using from_iterable () + product () + items ()
A combination of the above functions can be used to accomplish this specific task. The from_iterable () function can be used to shorten the inner loop, and the items function can be used to extract key-value pairs from a dictionary.

# Python3 code to demonstrate how it works
# Loop through a dictionary of lists of values ​​
# Using from_iterable () + product () + items ()

import itertools

 
# Initialize dictionary

test_dict = { ’ gfg’ : [ 1 , 2 ], ’is’ : [ 4 , 5 ], ’best’ : [ 7 , 8 ]}

 
# print the original dictionary

print ( "The original dictionary:" +   str (test_dict))

 
# Loop through a dictionary of lists of values ​​
# Using from_iterable () + product () + items ()

res = []

for key, value in (

itertools.chain.from_iterable (

[itertools.product ((k,), v) for k, v in test_dict.items ()] )):

res.append (value)

 
# print result

print ( "The list values ​​of keys are:" + str (res))

Output:

The orig inal dictionary: {’best’: [7, 8], ’is’: [4, 5], ’gfg’: [1, 2]}
The list values ​​of keys are: [7, 8, 1, 2, 4, 5]