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:
dict()
dict(**kwargs)
dict(mapping, **kwargs)
dict(iterable, **kwargs)
If you call the dict() constructor without arguments, then you get an empty dictionary:
>>> 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:
>>> 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: