Python Glossary Русский

all Python 3Dictionaries (dict)term

Nested dictionaries

nesting

Dictionary values may be of any type, including other dictionaries. They are reached through a chain of keys.

Syntax

d[key1][key2]  |  d.get(k1, {}).get(k2)

Assignment does not create intermediate levels: d['a']['b'] = 1 raises KeyError when 'a' is missing — use d.setdefault('a', {}) or collections.defaultdict first. The d.get(k1, {}).get(k2) chain is safe for reading, though each call builds a throwaway empty dict. Also note that d.copy() is shallow: nested dictionaries stay shared with the original, so use copy.deepcopy() for a truly independent copy.

Examples

user = {'name': 'Alice', 'address': {'city': 'Moscow', 'zip': '101000'}}
print(user['address']['city'])  # → Moscow
user['address']['country'] = 'Russia'
print(user['address'])  # → {'city': 'Moscow', 'zip': '101000', 'country': 'Russia'}
print(user.get('phone', {}).get('mobile', 'N/A'))  # → N/A — безопасный доступ
db = {'alice': {'age': 30}, 'bob': {'age': 25}}
for name, info in db.items():
    print(name, info['age'])  # → alice 30 / bob 25
catalog = {}
catalog.setdefault('fruits', {})['apple'] = 1.5
catalog.setdefault('fruits', {})['banana'] = 0.8
print(catalog)  # → {'fruits': {'apple': 1.5, 'banana': 0.8}}
config = {'db': {'host': 'localhost', 'port': 5432}, 'debug': True}
config['db']['host'] = '192.168.1.1'
print(config['db'])  # → {'host': '192.168.1.1', 'port': 5432}

See also

Open in the full glossarydocs.python.orgReport an inaccuracy