More on Dictionaries in Python

This text is part of a Real Python tutorial by Leodanis Pozo Ramos. It carries on from the earlier text-based lesson about dictionaries.


The dict() Constructor

You can also build dictionaries with the dict() constructor. The arguments to dict() can be a series of keyword arguments, another mapping, or an iterable of key-value pairs. Here are the constructor’s signatures:

Language: Python Syntax
dict()
dict(**kwargs)
dict(mapping, **kwargs)
dict(iterable, **kwargs)

If you call the dict() constructor without arguments, then you get an empty dictionary:

Language: Python
>>> dict()
{}

In most cases, you’ll use an empty pair of curly braces to create empty dictionaries. However, in some situations, using the constructor might be more explicit.

If the keys of your dictionary are strings representing valid Python identifiers, then you can specify them as keyword arguments. Here’s how you’d create the MLB_teams dictionary with this approach:

Language: Python
>>> MLB_teams = dict(
...     Colorado="Rockies",
...     Chicago="White Sox",
...     Boston="Red Sox",
...     Minnesota="Twins",
...     Milwaukee="Brewers",
...     Seattle="Mariners",
... )

>>> MLB_teams
{
    'Colorado': 'Rockies',
    'Chicago': 'White Sox',
    'Boston': 'Red Sox',
    'Minnesota': 'Twins',
    'Milwaukee': 'Brewers',
    'Seattle': 'Mariners'
}

Again, to build a dictionary using keyword arguments, the keys must be strings holding valid Python names. Otherwise, they won’t work as argument names. This is a syntactical restriction of Python.

You can also create a dictionary from an iterable of key-value pairs. Here’s how you can build the MLB_teams dictionary this way:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Already a member? Sign-In

You must own this product to join the conversation.