How to Create a Dictionary in Python
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
<dictionary> = {<key>: <value>, <key>: <value>}
<dictionary>[<new key>] = <value>
| Part | What 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.](https://strdewiridedevblogsprod.blob.core.windows.net/images/blog/programming/python/2026/py-dict-literal-code.webp)
book = {"title": "Dune", "author": "Frank Herbert", "year": 1965}
book["pages"] = 412
print(book)
Step 2: Run It
uv run python main.py
{'title': 'Dune', 'author': 'Frank Herbert', 'year': 1965, 'pages': 412}

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
| Mistake | What happens | Do 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 braces | SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='? | Write key: value |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
KeyError: '…' | The key is misspelled or was never added | Print the dictionary and compare the keys |
| A value you set earlier is gone | The same key was assigned again | Use 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
- Dictionaries, in the Python tutorial.
- Mapping types: dict, in the Python documentation.
