0
0
PythonHow-ToBeginner · 3 min read

How to Create a Dictionary in Python: Syntax and Examples

In Python, you create a dictionary using curly braces {} with key-value pairs separated by colons, like {'key': 'value'}. You can also use the dict() function to create dictionaries from pairs or other data structures.
📐

Syntax

A Python dictionary is created by enclosing key-value pairs in curly braces {}. Each key is separated from its value by a colon :, and pairs are separated by commas.

Example syntax:

  • {key1: value1, key2: value2}
  • Keys must be unique and immutable (like strings or numbers).
  • Values can be any data type.
python
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
💻

Example

This example shows how to create a dictionary with three key-value pairs and print it.

python
person = {'name': 'Bob', 'age': 25, 'city': 'London'}
print(person)
Output
{'name': 'Bob', 'age': 25, 'city': 'London'}
⚠️

Common Pitfalls

Common mistakes when creating dictionaries include:

  • Using duplicate keys, which will overwrite earlier values.
  • Using mutable types like lists as keys, which is not allowed.
  • Forgetting commas between pairs, causing syntax errors.
python
wrong_dict = {'a': 1, 'a': 2}  # Duplicate keys, 'a' will have value 2

# Correct way:
correct_dict = {'a': 1, 'b': 2}

# Wrong key type:
# invalid_dict = {[1, 2]: 'value'}  # Error: list is unhashable

# Correct key type:
valid_dict = {(1, 2): 'value'}
📊

Quick Reference

  • Use {} with key-value pairs to create dictionaries.
  • Keys must be immutable types like strings, numbers, or tuples.
  • Values can be any type, including other dictionaries.
  • Use dict() to create dictionaries from lists of pairs or keyword arguments.

Key Takeaways

Create dictionaries using curly braces with key-value pairs separated by colons.
Keys must be unique and immutable; values can be any data type.
Avoid duplicate keys and mutable types as keys to prevent errors.
Use the dict() function as an alternative way to create dictionaries.
Always separate pairs with commas to avoid syntax errors.