Mastering Python Dictionaries: Creation, Manipulation, and Advanced Techniques
Python Dictionary
This comprehensive guide explains Python dictionaries—how to create them, access, add, delete elements, and leverage built‑in methods.
Video: Python Dictionaries to Store key/value Pairs
Python dictionaries are unordered collections of key/value pairs. Each entry associates a unique, immutable key with a value that can be of any type.
Creating a Python Dictionary
Defining a dictionary is straightforward: place comma‑separated key/value pairs inside curly braces {}. Keys must be immutable (strings, numbers, or tuples of immutable elements) and unique; values may be any data type and can repeat.
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence of pairs
my_dict = dict([(1,'apple'), (2,'ball')])
All of the above approaches create the same dictionary structure.
Accessing Elements from a Dictionary
Dictionary values are retrieved via their keys, either with square brackets [] or the get() method. Using brackets raises a KeyError if the key is absent; get() returns None by default.
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# Trying to access a missing key returns None
print(my_dict.get('address'))
# KeyError
print(my_dict['address'])
Output
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'
Changing and Adding Dictionary Elements
Dictionaries are mutable. Assigning to an existing key updates its value; assigning to a new key adds a fresh entry.
# Changing and adding dictionary elements
my_dict = {'name': 'Jack', 'age': 26}
# update value
my_dict['age'] = 27
# Output: {'age': 27, 'name': 'Jack'}
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)
Output
{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}
Removing Elements from a Dictionary
Use pop() to delete a specific key and retrieve its value. popitem() removes an arbitrary pair, while clear() wipes the entire dictionary. The del keyword can remove individual entries or the entire variable.
# Removing elements from a dictionary
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value
# Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
# remove an arbitrary item, return (key,value)
# Output: (5, 25)
print(squares.popitem())
# Output: {1: 1, 2: 4, 3: 9}
print(squares)
# remove all items
squares.clear()
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# Throws Error
print(squares)
Output
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}
Traceback (most recent call last):
File "<string>", line 30, in <module>
print(squares)
NameError: name 'squares' is not defined
Python Dictionary Methods
The table below lists common dictionary methods and their purposes. Many are demonstrated in the examples that follow.
| Method | Description |
|---|---|
| clear() | Removes all items from the dictionary. |
| copy() | Returns a shallow copy of the dictionary. |
| fromkeys(seq[, v]) | Creates a new dictionary from seq with every key set to v (default None). |
| get(key[,d]) | Returns the value for key; if absent, returns d (default None). |
| items() | Returns a view of the dictionary’s (key, value) pairs. |
| keys() | Returns a view of the dictionary’s keys. |
| pop(key[,d]) | Deletes key and returns its value or d; raises KeyError if key is missing and d isn’t supplied. |
| popitem() | Removes and returns an arbitrary (key, value) pair; raises KeyError if the dictionary is empty. |
| setdefault(key[,d]) | Returns the value for key; if absent, inserts key with value d (default None) and returns d. |
| update([other]) | Inserts or updates key/value pairs from other, overwriting existing keys. |
| values() | Returns a view of the dictionary’s values. |
Example usage:
# Dictionary Methods
marks = {}.fromkeys(['Math', 'English', 'Science'], 0)
# Output: {'English': 0, 'Math': 0, 'Science': 0}
print(marks)
for item in marks.items():
print(item)
# Output: ['English', 'Math', 'Science']
print(list(sorted(marks.keys())))
Output
{'Math': 0, 'English': 0, 'Science': 0}
('Math', 0)
('English', 0)
('Science', 0)
['English', 'Math', 'Science']
Python Dictionary Comprehension
Dictionary comprehension offers a concise syntax for building dictionaries from iterables. It follows the pattern {key: value for element in iterable}.
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Equivalent imperative version:
squares = {}
for x in range(6):
squares[x] = x*x
print(squares)
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Comprehensions can include multiple loops and if filters. Example: only odd squares.
# Dictionary Comprehension with if conditional
odd_squares = {x: x*x for x in range(11) if x % 2 == 1}
print(odd_squares)
Output
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
For more on dictionary comprehensions, see Python Dictionary Comprehension.
Other Dictionary Operations
Dictionary Membership Test
Use the in operator to check if a key exists; it does not inspect values.
# Membership Test for Dictionary Keys
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: True
print(1 in squares)
# Output: True
print(2 not in squares)
# membership tests for key only not value
# Output: False
print(49 in squares)
Output
True True False
Iterating Through a Dictionary
Iterate over keys directly, then access values.
# Iterating through a Dictionary
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
Output
1 9 25 49 81
Dictionary Built‑in Functions
Standard functions such as all(), any(), len(), and sorted() are frequently applied to dictionaries.
| Function | Description |
|---|---|
| all() | True if every key evaluates to True (or if the dictionary is empty). |
| any() | True if any key evaluates to True; False for an empty dictionary. |
| len() | Number of key/value pairs. |
| cmp() | Compares two dictionaries (removed in Python 3). |
| sorted() | Returns a sorted list of keys. |
Examples:
# Dictionary Built‑in Functions
squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: False
print(all(squares))
# Output: True
print(any(squares))
# Output: 6
print(len(squares))
# Output: [0, 1, 3, 5, 7, 9]
print(sorted(squares))
Output
False True 6 [0, 1, 3, 5, 7, 9]
Python
- Mastering Python Data Types: A Practical Guide
- Mastering Python Operators: A Comprehensive Guide
- Mastering Python's While Loop: Syntax, Examples, and Best Practices
- Mastering the Python Pass Statement: A Practical Guide
- Master Python Functions: Syntax, Types, and Practical Examples
- Mastering Python Function Arguments: Positional, Keyword, and Default Parameters
- Python Packages: Structure, Importing, and Best Practices
- Python List Operations: Creation, Access, Modification, and Advanced Techniques
- Mastering Python Tuples: Creation, Access, and Advanced Operations
- Python Dictionary Fundamentals: Keys, Values, and Access