Constructing a python dictionary object using iterable

Overview:

The python dictionary keys can be taken from an iterable object and initialized with a value for each of the keys.

Example 1:

# Example Python program that creates
# Python dictionary from an iterable
roadList = ["Road1",
             "Road2",
             "Road3",
             "Road4",
             "Road5"];

# All roads lead to Rome
roadVsDestination = {i:'Rome' for i in roadList};
print(roadVsDestination);

Output:

{'Road1': 'Rome', 'Road2': 'Rome', 'Road3': 'Rome', 'Road4': 'Rome', 'Road5': 'Rome'}

Example 2:

# Example Python program that creates a dictionary
# from an iterable using range()
d = {i:i*3 for i in range(0, 10, 2)};
print("Dictionary:");
print(d);
print("Dictionary keys:");
print(d.keys());

Output:

Dictionary:
{0: 0, 2: 6, 4: 12, 6: 18, 8: 24}
Dictionary keys:
dict_keys([0, 2, 4, 6, 8])


Copyright 2024 © pythontic.com