Creating a Dictionary in Python

How can we create a dictionary in Python using the dict function or curly bracket notation?

There are two ways to create a dictionary in Python: using the dict function or curly bracket notation. The dict function is a built-in Python function that takes an iterable of key-value pairs as its argument and returns a dictionary object. On the other hand, curly bracket notation involves creating a dictionary using curly braces { }.

Using the dict function:

The dict function is a convenient way to create a dictionary in Python. You can pass key-value pairs to the dict function as arguments to create the dictionary. Here's an example:

python = dict([('name', 'John'), ('age', 30), ('city', 'New York')])

This line of code creates a dictionary with keys 'name', 'age', and 'city', and their respective values assigned. The resulting dictionary is stored in the variable python.

Using curly bracket notation:

Curly bracket notation allows you to create a dictionary by directly specifying key-value pairs within curly braces { }. Here's an example:

python = {'name': 'John', 'age': 30, 'city': 'New York'}

With this code snippet, a dictionary with the same key-value pairs as the previous example is created and stored in the variable python.

Both methods will result in the same dictionary object being created and assigned to the variable. The choice between using the dict function or curly bracket notation is mostly a matter of personal preference and readability. Some developers prefer the explicitness of the dict function, while others find the curly bracket notation cleaner and more concise.

← Which server rack is suitable for bolt free mounting Exploring the functions of verbal communication in communication skills →