10 Examples to Master Python Dictionary Comprehensions | by Soner Yıldırım | Jan, 2021

0
42

Example 10

The keys of a dictionary should be immutable so tuples can be utilized as keys. Dictionary comprehensions permit for producing keys of tuples by carried out nested loops.

a = [1,2,3]
b = [5,6]
dct = {(i,j):i*j for i in a for j in b}print(dct)
{(1, 5): 5,
(1, 6): 6,
(1, 7): 7,
(2, 5): 10,
(2, 6): 12,
(2, 7): 14,
(3, 5): 15,
(3, 6): 18,
(3, 7): 21,
(4, 5): 20,
(4, 6): 24,
(4, 7): 28}

Each pair of things within the lists is a key within the dictionary. The worth is the made from the pieces in keys.

The an identical for loop syntax:

LEAVE A REPLY

Please enter your comment!
Please enter your name here