Dictionary Basics

Difficulty: Intermediate

A dictionary in Python is a mutable, unordered (as of Python 3.6, insertion-ordered in CPython, guaranteed from 3.7+) collection of key-value pairs. Dictionaries are one of the most versatile and commonly used data structures in Python, offering O(1) average-case time complexity for lookups, insertions, and deletions. They are implemented using hash tables under the hood.

You can create a dictionary using curly braces {} with key: value pairs, using the dict() constructor, or by passing keyword arguments to dict(). Keys must be immutable (hashable) types such as strings, numbers, or tuples of immutables. Values can be any Python object. Duplicate keys are not allowed; assigning to an existing key overwrites the previous value.

Accessing values can be done using square bracket notation dict[key], which raises a KeyError if the key is missing, or using the get() method, which returns None (or a specified default) when the key is not found. The get() method is the safer choice when you are unsure whether a key exists.

The keys(), values(), and items() methods return view objects that reflect changes to the dictionary in real time. keys() returns all keys, values() returns all values, and items() returns tuples of (key, value) pairs. These views are iterable and support membership testing with the in operator. In Python 3, these return view objects rather than lists, so wrap them in list() if you need an actual list.

Checking for key existence is done with the in operator on the dictionary itself (key in dict), which is an O(1) operation. You can also use len() to get the number of key-value pairs, and bool() or a simple truthiness check to see if a dictionary is empty.

Code examples

Creating dictionaries

# Literal syntax
student = {'name': 'Alice', 'age': 22, 'grade': 'A'}
print(student)

# dict() constructor with keyword arguments
config = dict(host='localhost', port=3000, debug=True)
print(config)

# From list of tuples
pairs = [('x', 10), ('y', 20), ('z', 30)]
coords = dict(pairs)
print(coords)

# Empty dict
empty = {}
print(type(empty), len(empty))

Dictionaries can be created using literal curly brace syntax, the dict() constructor with keyword arguments, or by passing an iterable of key-value pairs. Python preserves insertion order (guaranteed from 3.7+).

Accessing values with [] and get()

person = {'name': 'Bob', 'age': 30, 'city': 'Mumbai'}

# Square bracket access
print(person['name'])
print(person['age'])

# get() with default
print(person.get('city'))
print(person.get('email', 'Not provided'))
print(person.get('phone'))

Square brackets raise KeyError for missing keys. The get() method returns None by default for missing keys, or a custom default value if specified as the second argument. Use get() when a key might not exist.

keys(), values(), and items()

scores = {'math': 95, 'science': 88, 'english': 92}

print('Keys:', list(scores.keys()))
print('Values:', list(scores.values()))
print('Items:', list(scores.items()))

# Iterating with items()
for subject, score in scores.items():
    print(f'{subject}: {score}')

# Membership test
print('math' in scores)
print('history' in scores)

keys(), values(), and items() return view objects that reflect the current state of the dict. Unpacking in for loops with items() is the Pythonic way to iterate over both keys and values. The in operator checks for key membership in O(1) time.

Dictionary length and truthiness

inventory = {'apples': 5, 'bananas': 3, 'oranges': 8}
print('Length:', len(inventory))
print('Is non-empty:', bool(inventory))

empty_dict = {}
print('Empty length:', len(empty_dict))
print('Is non-empty:', bool(empty_dict))

# Common pattern: check before access
data = {'results': [1, 2, 3]}
if data:
    print('Data has', len(data), 'key(s)')
if 'results' in data:
    print('Results:', data['results'])

len() returns the number of key-value pairs. An empty dictionary is falsy, and a non-empty dictionary is truthy. This allows clean if dict: checks before processing.

Key points

Concepts covered

dict creation, key access, get(), keys(), values(), items()