python

How to Create Dictionary From A Sequence in Python


In this article, you will learn how to create a dictionary from a sequence in Python.

Let’s say you have a sequence of cardinal directions.

keys = {'North', 'South', 'East', 'West'}

Create Dictionary From A Sequence in Python

In order to create a dictionary with keys and values, you can use the dict.fromkeys() method.

keys = {'North', 'South', 'East', 'West'}

# Value for the sequence of keys
value = 'Cardinal Direction'

# Display dictionary
print(dict.fromkeys(keys, value))
# {'North': 'Cardinal Direction', 'West': 'Cardinal Direction', 'East': 'Cardinal Direction', 'South': 'Cardinal Direction'}

Note: The dict.fromkeys() method functions by creating a dictionary from a sequence of keys with value


Share on social media

//