Skip to main content

How to Create a Dictionary in Python

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

A dictionary stores values under names, called keys: a book's title under "title", its year under "year". You write one in Python with curly braces and key: value pairs, and add more pairs at any time.

Syntax​

Syntax
<dictionary> = {<key>: <value>, <key>: <value>}
<dictionary>[<new key>] = <value>
PartWhat it does
{ ... }Creates a dictionary. {} on its own is an empty one.
<key>: <value>One pair. Keys are usually strings; each key appears once.
<dictionary>[<new key>] = <value>Adds a pair, or replaces the value of a key that already exists.

The Python tutorial: "Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output."

The Example​

The example describes a book with three pairs, adds the number of pages, and prints the result.

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2.

Step 1: Write the Dictionary​

Create a file named main.py:

main.py, which creates book with the title Dune, the author Frank Herbert and the year 1965, sets book["pages"] to 412 and prints book.

main.py
book = {"title": "Dune", "author": "Frank Herbert", "year": 1965}

book["pages"] = 412

print(book)

Step 2: Run It​

Terminal
uv run python main.py
Output
{'title': 'Dune', 'author': 'Frank Herbert', 'year': 1965, 'pages': 412}

A zsh terminal where uv run python main.py prints the book dictionary with title, author, year and pages.

The new pages pair appears last: dictionaries keep the order you added keys in. The command is the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Repeating a key, as in {'a': 1, 'a': 2}Only the last value is kept: {'a': 2}Use each key once
Reading a key that isn't there, as in book['isbn']KeyError: 'isbn'Add the key first, or read it with book.get('isbn')
Using = instead of : inside the bracesSyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?Write key: value

Troubleshooting​

SymptomLikely causeFix
KeyError: '…'The key is misspelled or was never addedPrint the dictionary and compare the keys
A value you set earlier is goneThe same key was assigned againUse a different key for each value

FAQ​

Is there another way to create a dictionary?​

Yes: dict(title="Dune", year=1965) builds the same kind of dictionary from keyword arguments, when the keys are valid Python names.

Can a value be a list or another dictionary?​

Yes. A value can be anything, such as {"genres": ["sci-fi", "classic"]}.

Conclusion​

Curly braces with key: value pairs create a dictionary, and dictionary[key] = value adds or replaces a pair. Keys are unique and stay in the order you added them.

Additional Resources​