Python Dictionary: How to Create, Access, and Modify

By 

Updated on

5 min read

Python Dictionary

A dictionary is a general-purpose data structure used to store key-value pairs. It is also known as an associative array, symbol table, or map. Dictionaries are helpful when working with structured data.

This article explains Python dictionaries with practical examples: how to create them, access values, update entries, and remove items.

Python Dictionaries

Dictionaries store data as key-value pairs. Each key must be unique and hashable, and each key maps to a value.

A dictionary is defined by enclosing a comma-separated list of key-value pairs in curly braces ({}):

py
dictionary_name = {key1: value1, key2: value2}
  • A comma (,) separates key-value pairs.
  • A colon (:) separates each key from its value.

Creating a Dictionary

You can create a dictionary using curly braces or the dict() constructor:

py
d = {"osname": "Ubuntu", "osversion": "24.04 LTS"}
py
d = dict(osname="Ubuntu", osversion="24.04 LTS")

You can also create a copy of another dictionary:

py
sysos = {"osname": "Ubuntu", "osversion": "24.04 LTS"}
newsysos = sysos.copy()

Access Dictionary Values

Access values by key using square brackets:

py
nums = {"num1": 400, "num2": 300, "num3": 100}
nums["num3"]
output
100

If the key does not exist, Python raises a KeyError:

py
nums["num4"]
output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'num4'

Use in to check whether a key exists:

py
"num4" in nums
"num3" in nums
output
False
True

Use get() to read a key safely and return a default value if the key is missing:

py
nums.get("num4", 0)
output
0

Update a Dictionary

Update existing values or add new key-value pairs by assigning to a key:

py
nums = {"num1": 100, "num2": 200}
nums["num1"] = 300
nums["num3"] = 400
nums
output
{'num1': 300, 'num2': 200, 'num3': 400}

You can also update multiple values at once using update():

py
nums.update({"num2": 250, "num4": 500})

Delete Items

To delete a key-value pair, use del or pop():

py
nums = {"num1": 100, "num2": 200}
del nums["num1"]
nums
output
{'num2': 200}
py
nums.pop("num2")
output
200

To delete all items, use clear():

py
nums.clear()
nums
output
{}

Dictionary Properties

Keys

Only immutable types are allowed as dictionary keys. A list, for example, is mutable, so it cannot be used as a key:

py
state = {[10, 20]: 90}
output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Common key types include:

  • Integers
  • Floats
  • Strings
  • Booleans
  • Tuples
py
state = {"Texas": "Austin", 50: "California", ("New York", 80): 90, True: [10, 20, 30], 19.09: (1, 2, 3)}

Keys must be unique. If duplicate keys are used, the last value wins:

py
employee_info = {"name": "Jack Smith", "age": 40, "experience": "20 years", "age": 92}
employee_info
output
{'name': 'Jack Smith', 'age': 92, 'experience': '20 years'}

Values

Values can be of any data type, including another dictionary or a list:

py
def addr():
    return ["124C - Maryland", "USA", "N. America"]

student_info = {"name": "Jack Smith", "age": 24, "degree": True, "address": addr()}
student_info.values()
output
dict_values(['Jack Smith', 24, True, ['124C - Maryland', 'USA', 'N. America']])

Dictionaries Are Mutable and Ordered

Dictionaries are mutable, so you can update or delete items after creation. In Python 3.7 and later, dictionaries preserve insertion order.

Nested Dictionaries

You can nest dictionaries inside other dictionaries, which is useful for structured data:

py
students = {
    "class A": {
        "name": "Jack Smith",
        "team": "Blue",
    },
    "class B": {
        "name": "Lisa",
        "team": "Green",
    },
}

students["class B"]["name"]
output
'Lisa'

Dictionary Comprehension

Use a dictionary comprehension to build a dictionary from an iterable:

py
nums = [1, 2, 3]
squares = {n: n * n for n in nums}
output
{1: 1, 2: 4, 3: 9}

Iterating Over Dictionaries

You can loop through a dictionary using a for loop.

Loop through keys:

py
student = {"name": "Jack", "age": 24, "degree": "CS"}
for key in student:
    print(key)
output
name
age
degree

Loop through values:

py
for value in student.values():
    print(value)
output
Jack
24
CS

Loop through both keys and values:

py
for key, value in student.items():
    print(f"{key}: {value}")
output
name: Jack
age: 24
degree: CS

Merging Dictionaries

You can merge two dictionaries using update():

py
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
dict1.update(dict2)
dict1
output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

In Python 3.9 and later, use the | operator to merge dictionaries:

py
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = dict1 | dict2
output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Use |= to update a dictionary in place:

py
dict1 |= dict2

Common Dictionary Methods

  • keys() - Return all keys.
  • values() - Return all values.
  • items() - Return key-value pairs.
  • get(key, default) - Return value or default.
  • update() - Update multiple items.
  • pop(key) - Remove a key and return its value.
  • popitem() - Remove and return the last inserted item.
  • clear() - Remove all items.
py
student_info = {"name": "Jack Smith", "age": 24, "degree": True}
student_info.items()
output
dict_items([('name', 'Jack Smith'), ('age', 24), ('degree', True)])

Quick Reference

OperationSyntax
Create dictionaryd = {"key": "value"}
Access valued["key"] or d.get("key")
Add/Update itemd["key"] = "value"
Delete itemdel d["key"] or d.pop("key")
Check if key exists"key" in d
Get all keysd.keys()
Get all valuesd.values()
Get all itemsd.items()
Merge dictionariesd1.update(d2) or d1 | d2
Clear dictionaryd.clear()

Conclusion

Python dictionaries store data as key-value pairs. You can create them, read values by key, update items, and remove entries as needed.

Tags

Linuxize Weekly Newsletter

A quick weekly roundup of new tutorials, news, and tips.

About the authors

Dejan Panovski

Dejan Panovski

Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 800+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.

View author page