← 输入框|python.land|刷新

Python Dictionary: How To Create And Use, With Examples

A Python dictionary is a collection of key-value pairs. You look up a value by its key instead of by its position, the way you look up a phone number by someone’s name. Keys are unique, and the type is called dict. You write a dictionary with curly braces, with a colon between each key and its value:

>>> phone_numbers = {'Jack': '070-02222748', 'Pete': '010-2488634'}
>>> phone_numbers['Jack']
'070-02222748'Code language: Python (python)

In other programming languages and computer science in general, dictionaries are also known as associative arrays, maps or hash maps. If you are familiar with JSON, you might feel right at home: the syntax of a dictionary strongly resembles that of a JSON document.

How to create a dictionary in Python

There are five common ways to create a dictionary in Python. Here they are side by side in the Python REPL, each building the same small dictionary of names and ages (except the comprehension, which computes its values):

>>> {'Jack': 32, 'Pete': 41}
{'Jack': 32, 'Pete': 41}
>>> dict(Jack=32, Pete=41)
{'Jack': 32, 'Pete': 41}
>>> dict([('Jack', 32), ('Pete', 41)])
{'Jack': 32, 'Pete': 41}
>>> names = ['Jack', 'Pete']
>>> ages = [32, 41]
>>> dict(zip(names, ages))
{'Jack': 32, 'Pete': 41}
>>> {name: len(name) for name in names}
{'Jack': 4, 'Pete': 4}
>>> dict.fromkeys(names, 0)
{'Jack': 0, 'Pete': 0}Code language: Python (python)
  • Curly braces (a dictionary literal) are what you’ll use most. Use them whenever you can type the data out.
  • dict() turns keyword arguments or a list of pairs into a dictionary.
  • dict(zip(keys, values)) combines two lists: one with keys, one with values.
  • A dictionary comprehension builds a dictionary from any iterable, computing keys and values as it goes.
  • dict.fromkeys() gives a list of keys the same starting value.

Each of these is explained in more detail below.

Create a dictionary with curly braces

A dictionary is created by using curly braces. Inside these braces, you add one or more key-value pairs, separated by commas. The dictionary below associates keys (names like Jack and Pete) with values (their phone numbers). The second one, my_empty_dict, is an empty dictionary:

>>> phone_numbers = {
...     'Jack': '070-02222748',
...     'Pete': '010-2488634',
... }
>>> my_empty_dict = {}
>>> phone_numbers['Jack']
'070-02222748'
>>> type(my_empty_dict)
<class 'dict'>Code language: Python (python)

When a dictionary gets longer than one line, put each pair on its own line like I did here. A comma after the last pair is allowed, and it makes adding another pair later a little easier.

One thing that trips people up: {} is an empty dictionary, not an empty set. For an empty set, you need set():

>>> type({})
<class 'dict'>
>>> type(set())
<class 'set'>Code language: Python (python)

If you’d like to practice this with exercises that check your code as you go, the lesson Create and Read a Dictionary in my Python Fundamentals course covers exactly this.

More ways to create a Python dictionary

Depending on where your data comes from, one of these other ways to create a dictionary might come in handy.

Using the dict() constructor

The dict() function can build a dictionary from keyword arguments, or from a sequence of key-value pairs (tuples). Called without arguments, it returns an empty dictionary:

>>> dict(name='Erik', language='Python', years=20)
{'name': 'Erik', 'language': 'Python', 'years': 20}
>>> dict([('Jack', '070-02222748'), ('Pete', '010-2488634'), ('Eric', '06-10101010')])
{'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010'}
>>> dict()
{}Code language: Python (python)

The keyword version saves you some quotes, but it only works when your keys are strings that are also valid Python names. A key like 'first-name' or 2024 needs the curly-brace syntax.

Create a dictionary from two lists with zip()

If you have one list with keys and another with values, zip() pairs them up, and dict() turns those pairs into a dictionary:

>>> names = ['Jack', 'Pete', 'Eric']
>>> numbers = ['070-02222748', '010-2488634', '06-10101010']
>>> dict(zip(names, numbers))
{'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010'}Code language: Python (python)

Be careful when the lists don’t have the same length. By default, zip() silently stops at the shortest list, so data goes missing without a warning. Pass strict=True (Python 3.10 and later) to get an error instead:

>>> dict(zip(['a', 'b', 'c'], [1, 2]))
{'a': 1, 'b': 2}
>>> dict(zip(['a', 'b', 'c'], [1, 2], strict=True))
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    dict(zip(['a', 'b', 'c'], [1, 2], strict=True))
    ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: zip() argument 2 is shorter than argument 1Code language: Python (python)

Dictionary Comprehensions

Analogous to list comprehensions, you can also use dictionary comprehensions to create a new dictionary. While a list only contains values, a dictionary contains key-value pairs. Hence, a dictionary comprehension needs to define both, separated by a colon. Other than that, the syntax is similar:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
>>> prices = {'apple': 0.40, 'pear': 0.65, 'mango': 1.80}
>>> {fruit: price for fruit, price in prices.items() if price < 1}
{'apple': 0.4, 'pear': 0.65}Code language: Python (python)

The second example loops over an existing dictionary and keeps only the cheap fruit. Filtering and transforming dictionaries like this is where comprehensions really shine. Please read my article on list comprehensions for a more detailed explanation of comprehensions in general.

Using dict.fromkeys

The dict.fromkeys(keys, value) method creates a new dictionary based on the keys supplied to it. Every key gets the same value, or None if you don’t supply one:

>>> names = ['Eric', 'Martha', 'Ellen']
>>> dict.fromkeys(names)
{'Eric': None, 'Martha': None, 'Ellen': None}
>>> dict.fromkeys(names, 0)
{'Eric': 0, 'Martha': 0, 'Ellen': 0}Code language: Python (python)

The keys can come from anything that is iterable. For example, this works just as well with a set or a tuple.

There’s one trap here. All keys share the very same value object. With numbers, strings or None that doesn’t matter, but with a list it does. Append to one, and you append to all of them. Use a dictionary comprehension if every key needs its own list:

>>> scores = dict.fromkeys(['Eric', 'Martha'], [])
>>> scores['Eric'].append(10)
>>> scores
{'Eric': [10], 'Martha': [10]}
>>> scores = {name: [] for name in ['Eric', 'Martha']}
>>> scores['Eric'].append(10)
>>> scores
{'Eric': [10], 'Martha': []}Code language: Python (python)

Parse a JSON object to a dictionary

As explained in the section on working with JSON, you can also decode JSON data into a dictionary like this:

>>> import json
>>> jsonstring = '{"name": "erik", "age": 38, "married": true}'
>>> json.loads(jsonstring)
{'name': 'erik', 'age': 38, 'married': True}Code language: Python (python)

Access values in a Python dictionary

To get a value out of a dictionary, put its key between square brackets. If the key doesn’t exist, Python raises a KeyError:

>>> phone_numbers = {'Jack': '070-02222748', 'Pete': '010-2488634'}
>>> phone_numbers['Pete']
'010-2488634'
>>> phone_numbers['Lisa']
Traceback (most recent call last):
  File "<python-input-2>", line 1, in <module>
    phone_numbers['Lisa']
    ~~~~~~~~~~~~~^^^^^^^^
KeyError: 'Lisa'Code language: Python (python)

Keys are matched exactly, so 'lisa' and 'Lisa' are two different keys.

Default values and dict.get()

Another way to retrieve a single value from a dictionary is the get() method. The advantage? It returns a default value, None, if the key was not found. You can specify your own default value too, as the second argument.

With get(), you don’t have to surround the lookup with a try... except. It’s ideal when working with configuration data that is parsed from YAML or JSON files, where your software offers defaults for unset configuration items. An example:

>>> config = {'host': 'example.org'}
>>> config.get('host')
'example.org'
>>> config.get('port', 80)
80
>>> config.get('schema')
>>> print(config.get('schema'))
NoneCode language: Python (python)

The config.get('schema') call returns None, but the REPL doesn’t print None, so you see nothing. Wrap it in print() to see it.

So which one should you use? Use square brackets when the key should be there, so a missing key shows up as an error instead of hiding a bug. Use get() when a missing key is normal and you have a sensible default.

Check if a key exists in a Python dictionary

You can check if a key exists inside a dictionary with the in and not in keywords. Note that in looks at the keys only. To check for a value, use in on values():

>>> phone_numbers = {'Jack': '070-02222748', 'Pete': '010-2488634'}
>>> 'Jack' in phone_numbers
True
>>> 'Lisa' in phone_numbers
False
>>> 'Lisa' not in phone_numbers
True
>>> '070-02222748' in phone_numbers
False
>>> '070-02222748' in phone_numbers.values()
TrueCode language: Python (python)

Checking for a key goes well with an if statement:

>>> phone_numbers = {'Jack': '070-02222748', 'Pete': '010-2488634'}
>>> name = 'Lisa'
>>> if name in phone_numbers:
...     print(phone_numbers[name])
... else:
...     print(f'No number for {name}')
... 
No number for LisaCode language: Python (python)

Checking keys with in is fast, even for huge dictionaries, because Python doesn’t search through them one by one. Checking values with in on values() does go through every value, so that gets slower as the dictionary grows.

Add and overwrite dictionary entries

To add an entry, assign a value to a new key. To overwrite an entry, assign a new value to an existing key. It’s the same syntax, and you don’t need to del the old entry first:

>>> phone_numbers = {'Jack': '070-02222748', 'Pete': '010-2488634'}
>>> phone_numbers['Eric'] = '06-10101010'
>>> phone_numbers['Jack'] = '1234567'
>>> phone_numbers
{'Jack': '1234567', 'Pete': '010-2488634', 'Eric': '06-10101010'}Code language: Python (python)

Add or update several entries with update()

The update() method adds all pairs from another dictionary (or from keyword arguments) in one go. Existing keys get the new value:

>>> phone_numbers = {'Jack': '070-02222748', 'Pete': '010-2488634'}
>>> phone_numbers.update({'Pete': '010-1111111', 'Lisa': '020-5555555'})
>>> phone_numbers
{'Jack': '070-02222748', 'Pete': '010-1111111', 'Lisa': '020-5555555'}
>>> phone_numbers.update(Martha='030-1234567')
>>> phone_numbers
{'Jack': '070-02222748', 'Pete': '010-1111111', 'Lisa': '020-5555555', 'Martha': '030-1234567'}Code language: Python (python)

Add a key only if it’s missing with setdefault()

setdefault(key, value) returns the value of the key if it exists. If it doesn’t, it inserts the key with the value you gave and returns that:

>>> stock = {'apples': 10}
>>> stock.setdefault('apples', 0)
10
>>> stock.setdefault('pears', 0)
0
>>> stock
{'apples': 10, 'pears': 0}Code language: Python (python)

A very common pattern combines adding and get(): counting how often something occurs. Each word starts at 0 when it’s not in the dictionary yet:

>>> words = ['spam', 'eggs', 'spam', 'ham', 'spam']
>>> counts = {}
>>> for word in words:
...     counts[word] = counts.get(word, 0) + 1
... 
>>> counts
{'spam': 3, 'eggs': 1, 'ham': 1}Code language: Python (python)

Delete a key-value pair: del, pop() and popitem()

To remove an entry from a dictionary, use the del statement with the key. Like square brackets, it raises a KeyError if the key isn’t there:

>>> phone_numbers = {'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010'}
>>> del phone_numbers['Jack']
>>> phone_numbers
{'Pete': '010-2488634', 'Eric': '06-10101010'}
>>> del phone_numbers['Lisa']
Traceback (most recent call last):
  File "<python-input-3>", line 1, in <module>
    del phone_numbers['Lisa']
        ~~~~~~~~~~~~~^^^^^^^^
KeyError: 'Lisa'Code language: Python (python)

If you also want the value you removed, use pop(). Give it a second argument to get that instead of an error when the key is missing. popitem() removes the last inserted pair and returns it as a tuple, and clear() empties the whole dictionary:

>>> phone_numbers = {'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010'}
>>> phone_numbers.pop('Pete')
'010-2488634'
>>> phone_numbers.pop('Lisa', None)
>>> phone_numbers
{'Jack': '070-02222748', 'Eric': '06-10101010'}
>>> phone_numbers.popitem()
('Eric', '06-10101010')
>>> phone_numbers
{'Jack': '070-02222748'}
>>> phone_numbers.clear()
>>> phone_numbers
{}Code language: Python (python)

Calling popitem() on an empty dictionary gives a KeyError too:

>>> {}.popitem()
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    {}.popitem()
    ~~~~~~~~~~^^
KeyError: 'popitem(): dictionary is empty'Code language: Python (python)

Loop over a Python dictionary

When you loop over a dictionary with a Python for-loop, you get its keys. To loop over the values, use the values() method:

>>> phone_numbers = {'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010'}
>>> for name in phone_numbers:
...     print(name)
... 
Jack
Pete
Eric
>>> for number in phone_numbers.values():
...     print(number)
... 
070-02222748
010-2488634
06-10101010Code language: Python (python)

dict.items(): loop through a Python dictionary

Most of the time, you want both the key and the value. The items() method of a dictionary returns an iterable view object with both, as key-value tuples. In a for-loop, you can unpack each tuple into two variables right away:

>>> phone_numbers.items()
dict_items([('Jack', '070-02222748'), ('Pete', '010-2488634'), ('Eric', '06-10101010')])
>>> for name, number in phone_numbers.items():
...     print(f'{name}: {number}')
... 
Jack: 070-02222748
Pete: 010-2488634
Eric: 06-10101010Code language: Python (python)

Loops always visit the keys in insertion order, which I explain in more detail further down.

Don’t change a dictionary’s size while you loop over it

Adding or removing keys while you loop over the same dictionary raises a RuntimeError:

>>> stock = {'apples': 0, 'pears': 4, 'mangos': 0}
>>> for fruit in stock:
...     if stock[fruit] == 0:
...         del stock[fruit]
... 
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    for fruit in stock:
                 ^^^^^
RuntimeError: dictionary changed size during iterationCode language: Python (python)

There are two easy fixes. Loop over a copy of the keys with list(), or build a new dictionary with a comprehension that keeps only what you want:

>>> stock = {'apples': 0, 'pears': 4, 'mangos': 0}
>>> for fruit in list(stock):
...     if stock[fruit] == 0:
...         del stock[fruit]
... 
>>> stock
{'pears': 4}
>>> stock = {'apples': 0, 'pears': 4, 'mangos': 0}
>>> {fruit: n for fruit, n in stock.items() if n > 0}
{'pears': 4}Code language: Python (python)

Changing the values of existing keys while looping is fine. It’s only adding and removing keys that causes the error.

Dictionary view objects

The keys(), values() and items() methods return a view object, offering a window on your dictionary’s keys and values. Before using such view objects, there’s an important concept you need to understand: values in a view object change as the content of the dictionary changes.

dict.keys() and dict.values()

This is best illustrated with an example, in which we use two of these views: keys() and values(). keys() returns a view on all the keys of a dictionary, while values() returns a view on all its values:

phone_numbers = {'Jack': '070-02222748',
                 'Pete': '010-2488634',
                 'Eric': '06-10101010'}
names = phone_numbers.keys()
numbers = phone_numbers.values()
phone_numbers['Linda'] = '030-987612312'
print(names)
print(numbers)

# Loop through a view object with:
for number in numbers:
    print(number)Code language: Python (python)

The output of this code is:

dict_keys(['Jack', 'Pete', 'Eric', 'Linda'])
dict_values(['070-02222748', '010-2488634', '06-10101010', '030-987612312'])
070-02222748
010-2488634
06-10101010
030-987612312Code language: Python (python)

As you can see, Linda is part of the keys too, even though she got added after creating the names view object.

More ways to get all the keys

We’ve seen the dict.keys() method, which returns a view object with all the dictionary keys. The advantage of this object is that it stays in sync with the dictionary. It’s perfect for looping over all the keys, but you still might opt for list() or sorted(), because those return a regular list that you can change, index and slice.

>>> phone_numbers = {'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010'}
>>> list(phone_numbers)
['Jack', 'Pete', 'Eric']
>>> sorted(phone_numbers)
['Eric', 'Jack', 'Pete']Code language: Python (python)

list() returns all the keys in insertion order, while sorted() returns all the keys sorted alphabetically.

Getting the length of a Python dictionary

The built-in Python len() function returns the number of key-value pairs in a dictionary:

>>> phone_numbers = {'Jack': '070-02222748', 'Pete': '010-2488634', 'Eric': '06-10101010'}
>>> len(phone_numbers)
3
>>> len({})
0Code language: Python (python)

Merging dictionaries

Since Python 3.9, you can merge two dictionaries with the | operator. It returns a new dictionary and leaves the originals alone. When both dictionaries have the same key, the value from the right-hand one wins:

>>> defaults = {'host': 'localhost', 'port': 80}
>>> user_settings = {'port': 8080, 'debug': True}
>>> defaults | user_settings
{'host': 'localhost', 'port': 8080, 'debug': True}
>>> defaults
{'host': 'localhost', 'port': 80}Code language: Python (python)

To merge into an existing dictionary instead, use |=. It changes the dictionary on the left in place, just like update():

>>> defaults |= user_settings
>>> defaults
{'host': 'localhost', 'port': 8080, 'debug': True}Code language: Python (python)

Before Python 3.9, the usual way was unpacking both dictionaries into a new one with **. You’ll still see this in a lot of code, and it still works:

>>> dict1 = {'a': 1, 'b': 2}
>>> dict2 = {'b': 3, 'c': 4}
>>> {**dict1, **dict2}
{'a': 1, 'b': 3, 'c': 4}Code language: Python (python)

Are Python dictionaries ordered?

Yes. Since Python 3.7, dictionaries are guaranteed to keep insertion order: the order of the keys is the order in which you added them. Overwriting the value of an existing key doesn’t move it. Deleting a key and adding it again puts it at the end:

>>> ages = {}
>>> ages['Pete'] = 41
>>> ages['Jack'] = 32
>>> ages['Eric'] = 28
>>> ages
{'Pete': 41, 'Jack': 32, 'Eric': 28}
>>> ages['Pete'] = 42
>>> ages
{'Pete': 42, 'Jack': 32, 'Eric': 28}
>>> del ages['Jack']
>>> ages['Jack'] = 33
>>> ages
{'Pete': 42, 'Eric': 28, 'Jack': 33}Code language: Python (python)

Dictionaries don’t have a sort method, but you can build a sorted copy. sorted() on the items, with a key function that picks the value, gives you the pairs ordered by value. dict() turns them back into a dictionary:

>>> ages = {'Pete': 41, 'Jack': 32, 'Eric': 28}
>>> dict(sorted(ages.items(), key=lambda item: item[1]))
{'Eric': 28, 'Jack': 32, 'Pete': 41}Code language: Python (python)

Even though dictionaries remember their order, you can’t access an entry by position. ages[0] looks for the key 0, not the first entry. If you need the first key, use list(ages)[0].

Comparing Python dictionaries

If you need to compare two dictionaries, use the == operator. Two dictionaries are equal when they have the same keys with the same values. A dictionary can contain objects of any type, so Python walks through all the keys and values and compares them one by one.

You might wonder if a dictionary with the same keys and values, inserted in another order, is the same. Let’s check this:

>>> first_dict = {'a': 1, 'b': 2, 'c': 'a string'}
>>> second_dict = {'b': 2, 'a': 1, 'c': 'a string'}
>>> first_dict == second_dict
TrueCode language: Python (python)

They are the same to Python, despite having a different order. Order matters when you loop, but not when you compare.

Valid dictionary values

You can put anything in a dictionary. You’re not limited to numbers or strings. In fact, you can put dictionaries and Python lists inside your dictionary and access the nested values in a very natural way:

>>> a = {'sub_dict': {'b': True}, 'mylist': [100, 200, 300]}
>>> a['sub_dict']['b']
True
>>> a['mylist'][0]
100Code language: Python (python)

Python’s JSON decoding and encoding library uses this feature of Python when parsing more complex JSON documents. It creates nested trees of lists, dictionaries, and other valid data types.

Nested dictionaries

A dictionary inside a dictionary is called a nested dictionary. It’s a natural way to store records, like a few details per user. You reach into it by chaining square brackets, one per level:

>>> users = {
...     'erik': {'email': 'erik@example.com', 'languages': ['Python', 'Go']},
...     'lisa': {'email': 'lisa@example.com', 'languages': ['Rust']},
... }
>>> users['erik']['email']
'erik@example.com'
>>> users['lisa']['languages'].append('Python')
>>> users['lisa']
{'email': 'lisa@example.com', 'languages': ['Rust', 'Python']}
>>> users['jack'] = {'email': 'jack@example.com', 'languages': []}
>>> len(users)
3
>>> for name, info in users.items():
...     print(name, info['email'])
... 
erik erik@example.com
lisa lisa@example.com
jack jack@example.comCode language: Python (python)

If any level might be missing, chained square brackets raise a KeyError at the first missing key. Chaining get() calls, with an empty dictionary as the default for the outer level, returns None instead:

>>> users.get('pete', {}).get('email')
>>> users['pete']['email']
Traceback (most recent call last):
  File "<python-input-8>", line 1, in <module>
    users['pete']['email']
    ~~~~~^^^^^^^^
KeyError: 'pete'Code language: Python (python)

Valid dictionary keys

You can go pretty wild on your dictionary keys, too. The only requirement is that the key is hashable. In practice, that means immutable: you can’t change it after creating it. Mutable types like lists, dictionaries, and sets won’t work:

>>> {['a', 'b']: 1}
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    {['a', 'b']: 1}
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')Code language: Python (python)

Besides this limitation, you can use all data types as a dictionary key, including native types like a tuple, float and int or even a class name or object based on a class. Although completely useless for most, I’ll demonstrate anyway:

>>> my_dictionary = {int: 1, float: 2, dict: 3}
>>> my_dictionary[dict]
3
>>> class P:
...     pass
... 
>>> my_dictionary[P] = 4
>>> p = P()
>>> my_dictionary[p] = 5
>>> len(my_dictionary)
5Code language: Python (python)

A more likely use case is the use of numbers as keys. For example, consider this registration of runners in a marathon:

>>> runners = {1000: 'Jack', 1001: 'Eric', 1002: 'Lisa'}
>>> runners[1001]
'Eric'Code language: Python (python)

Tuples make good keys when one value isn’t enough to identify something, like the distance between two cities:

>>> distances = {('Amsterdam', 'Paris'): 505, ('Amsterdam', 'Berlin'): 577}
>>> distances[('Amsterdam', 'Paris')]
505Code language: Python (python)

One surprise to be aware of: 1, 1.0 and True are equal in Python, so they count as the same key. The first key stays, and the last value wins:

>>> d = {1: 'int', 1.0: 'float', True: 'bool'}
>>> d
{1: 'bool'}Code language: Python (python)

Common Python dictionary errors

Most dictionary errors you’ll run into are one of these four. You’ve seen most of them above already, but it helps to have them in one place.

KeyError and using try… except

A KeyError means you asked for a key that isn’t in the dictionary. Check the spelling and capitalization first, since keys are matched exactly. If you know data can be missing, for example when parsing input from the outside world, you can use get() with a default, check with in first, or catch the exception with try... except:

>>> phone_numbers = {'Jack': '070-02222748'}
>>> try:
...     number = phone_numbers['Lisa']
... except KeyError:
...     number = 'unknown'
... 
>>> number
'unknown'Code language: Python (python)

I’ve explained this in detail in the best practices section of my article on try… except. In that article, I also explain the concept of asking for forgiveness, not permission: don’t check if a key exists before trying to access it. Instead, just try it, and catch the exception if it doesn’t exist.

TypeError: unhashable type

You used a mutable object, like a list, as a key. Before Python 3.14, the message was shorter: TypeError: unhashable type: 'list'. Use a tuple instead of a list, or a frozenset instead of a set. See valid dictionary keys.

RuntimeError: dictionary changed size during iteration

You added or removed keys inside a loop over the same dictionary. Loop over list(your_dict) instead, or build a new dictionary. See the loop section for both fixes.

AttributeError: ‘dict’ object has no attribute

You used dot notation, which works in JavaScript but not on a Python dictionary. Use square brackets:

>>> person = {'name': 'Erik'}
>>> person.name
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    person.name
AttributeError: 'dict' object has no attribute 'name'Code language: Python (python)

The fix is person['name'].

Built-in Python dictionary methods

Each dictionary comes with some handy built-in methods, as listed in the following table. Optional arguments are marked with square brackets:

MethodWhat it doesExample
clear()Remove all key-value pairs (empty the dictionary)phone_numbers.clear()
copy()Return a shallow copy of the dictionarybackup = phone_numbers.copy()
fromkeys(keys [, value])Create a new dictionary with the given keys, all set to the same value (called on dict itself)dict.fromkeys(['a', 'b'], 0)
get(key [, default_value])Get a single item with the given key, with an optional default valuephone_numbers.get('Martha', 'Unknown person')
items()Return a view object containing the key-value pairs from the dictionaryphone_numbers.items()
keys()Return a view object with all keys from the dictionaryphone_numbers.keys()
values()Return a view object with all values from the dictionaryphone_numbers.values()
pop(key [, default_value])Remove the element with the specified key and return its valuephone_numbers.pop('Martha')
popitem()Remove the last inserted item and return it as a tuplephone_numbers.popitem()
setdefault(key [, value])Return the value of the specified key. If the key does not exist, insert it with the given valuephone_numbers.setdefault('John Doe', '1234')
update(other)Add all pairs from another dictionary, an iterable of pairs, or keyword argumentsphone_numbers.update({'Lisa': '020-5555555'})
The built-in methods of a Python dictionary

Keep learning

Dictionaries are one of the data types you’ll use most in Python, together with lists. To see where they fit in with the other built-in types, have a look at the overview of Python data types. For every last detail, the official Python documentation has a reference page on the dict type and a section on dictionaries in the tutorial.

Related articles

4 thoughts on “Python Dictionary: How To Create And Use, With Examples”

  1. Hello Erick,

    I think in the table “Built-in Python dictionary methods”:

    – “Returns a view_object” but should be “Returns a view object with a ”
    – “get(key)” should be “get(key, default_value)”

    Thank you again for the tutorial!

  2. Hello, Erik! I use IDLE Shell 3.10.4. When I use a get-method to retrieve a value that is not included in the dictionary, Python does not return a default value, None. Why is this happening?
    I input:

    >>> phone_numbers.get('shema')Code language: Python (python)

    Then I press Enter and Python takes me to the next line, where I’m able to type further.
    Generally, it seems like this:

    >>> phone_numbers.get('shema')
    >>>Code language: Python (python)

    Thank you in advance)

    • Interesting. Perhaps it changed. Indeed the REPL doesn’t print None. You can still check it by explicitly printing the result, e.g. print(phone_numbers.get(‘not here’))

Leave a Comment