Constructing a python dictionary object using iterable

Create a python dictionary object with the key values from an iterable object

Dictionary Updated 10 Sep 2016 1 min read

Overview

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

Example 1

python
# 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

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

Example 2

python
# 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

Output
Dictionary:

            {0: 0, 2: 6, 4: 12, 6: 18, 8: 24}

            Dictionary keys:

            dict_keys([0, 2, 4, 6, 8])