Create Dictionary

 

What You'll Learn: In this tutorial, you'll discover different ways to create a dictionary in Python. A dictionary stores data in key-value pairs, which helps you organize and retrieve data efficiently.

1. Create a Dictionary through Initialization

You can initialize a set of key-value pairs to create a dictionary. Key-value pairs are of the form key:value, separated by commas and enclosed in curly braces {}.

Example Code:

python
myDict = {1: 'foo', 2: 'bar', 3: 'moo'}
print(type(myDict))
print(myDict)

Output:

<class 'dict'>
{1: 'foo', 2: 'bar', 3: 'moo'}

2. Create a Dictionary using dict() Built-in Function

You can build a dictionary from a sequence of key-value pairs using the dict() constructor.

Example Code:

python
myDict = dict([(1, 'foo'), (2, 'bar'), (3, 'moo')])
print(type(myDict))
print(myDict)

Output:

<class 'dict'>
{1: 'foo', 2: 'bar', 3: 'moo'}

3. Create a Dictionary by Passing Keyword Arguments to dict()

If keys are simple strings, you can specify key-value pairs as keyword arguments to the dict() constructor.

Example Code:

python
myDict = dict(a='foo', b='bar', c='moo')
print(type(myDict))
print(myDict)

Output:

<class 'dict'>
{'a': 'foo', 'b': 'bar', 'c': 'moo'}

4. Create a Dictionary using Dictionary Comprehensions

You can also create a dictionary using dictionary comprehension. This method is useful for creating dictionaries from sequences or ranges.

Example Code:

python
def someThing(x):
    return x ** 3
myDict = {x: someThing(x) for x in (5, 8, 9, 12)}
print(type(myDict))
print(myDict)

Output:

<class 'dict'>
{5: 125, 8: 512, 9: 729, 12: 1728}

Try It Yourself: Fun Exercises

  1. Create Your Dictionary:
    • Initialize a dictionary with your favorite movies and their release years.
  2. Using dict() Constructor:
    • Use the dict() function to create a dictionary with the names of your friends and their favorite colors.
  3. Dictionary Comprehension:
    • Create a dictionary where the keys are numbers and the values are the square of the numbers using dictionary comprehension.

Summary:

In this Python tutorial, we learned different ways to create dictionaries, including initialization, using the dict() function, passing keyword arguments, and using dictionary comprehension. These methods help you store and organize data efficiently. Keep experimenting and have fun with dictionaries in Python!