Skip to content

RESOURCES / BLOG

What is a Python Dictionary and How Do You Use It?

Hi everyone,

I’m fairly new to Python and I keep seeing something called a dictionary in tutorials and code examples. It looks a bit like a JSON object, and I’ve seen it used for all kinds of data like image metadata, settings, and API responses.

Can someone explain what a Python dictionary is, how it works, and maybe give me some beginner-friendly examples (bonus if it’s useful in web dev)?

Thanks in advance!

Great question! The Python dictionary is one of the most useful and powerful data types in Python. If you’ve used JSON, you’ll feel right at home; it’s the same key-value structure.

Dictionaries are perfect for storing related information, like metadata about an image, a user profile, or settings for an image processing tool like Cloudinary.

A dictionary in Python is a collection of key-value pairs.

Each key must be unique and immutable (like a string or number), and each key maps to a value, which can be any type (strings, numbers, lists, even other dictionaries!).

my_dict = {

    "key1": "value1",

    "key2": "value2"

}Code language: JavaScript (javascript)

Let’s say you’re working with an image and want to store information about it:

image_info = {

    "filename": "sunset.jpg",

    "width": 1920,

    "height": 1080,

    "format": "jpeg",

    "tags": ["nature", "sunset", "landscape"]

}Code language: JavaScript (javascript)

You can access values by their key:

print(image_info["filename"])  # sunset.jpg

print(image_info["tags"])      # ['nature', 'sunset', 'landscape']Code language: CSS (css)
user = {

    "name": "Alex",

    "email": "alex@example.com"

}

# Access

print(user["name"])  # Alex

# Add new key-value

user["age"] = 30

# Update value

user["email"] = "alex@newdomain.com"

# Delete a key

del user["age"]Code language: PHP (php)
if "email" in user:

    print("Email found!")Code language: PHP (php)
for key, value in image_info.items():

    print(f"{key}: {value}")

# Output: 

filename: sunset.jpg

width: 1920

height: 1080

format: jpeg

tags: ['nature', 'sunset', 'landscape']Code language: PHP (php)

This is perfect when you want to display or export metadata.

MethodDescription
dict.get(key)Safely access a key (returns None if it doesn’t exist)
dict.keys()Returns all keys
dict.values()Returns all values
dict.items()Returns all key-value pairs
dict.update()Updates dictionary with another dictionary

image_info.update({"format": "png", "compressed": True})

Need to store multiple images with their own metadata?

gallery = {

    "img1": {"filename": "beach.jpg", "tags": ["beach", "sun"]},

    "img2": {"filename": "forest.jpg", "tags": ["trees", "green"]}

}

print(gallery["img2"]["tags"])

# Output: ['trees', 'green']Code language: PHP (php)

This is especially useful for handling JSON data or API responses.

cloudinary_response = {

    "public_id": "myimage",

    "version": 16234567,

    "format": "jpg",

    "resource_type": "image",

    "url": "https://res.cloudinary.com/demo/image/upload/v16234567/myimage.jpg"

}

print(cloudinary_response["url"])Code language: PHP (php)

You can use this dictionary to programmatically access data or build UI elements.

FeatureDictionaryList
Access byKey (e.g., "name")Index (e.g., 0)
Keys must beUnique and immutableNot applicable
Ideal forLabeled data (like user info)Ordered data (like steps)

Use dictionaries when your data has labels or attributes (like image size or file type), and lists when you’re working with sequences.

KeyError: Trying to access a key that doesn’t exist.

# Wrong

value = my_dict["missing_key"# KeyError

# Right

value = my_dict.get("missing_key"# Returns NoneCode language: PHP (php)

Mutable keys: You can’t use lists or dictionaries as keys.

# Invalid

my_dict[[1, 2, 3]] = "value"Code language: PHP (php)

Want to build a dictionary from a list?

names = ["sunset", "beach", "mountain"]

lengths = {name: len(name) for name in names}

print(lengths)

# Output: {'sunset': 6, 'beach': 5, 'mountain': 8}Code language: PHP (php)

This is great for mapping metadata or dynamically generating configs.

The Python dictionary is one of the most powerful tools in your toolkit. It helps you manage structured data in an intuitive and readable way. Whether you’re handling API responses, organizing image metadata, or passing config settings to a Cloudinary transformation, dictionaries are your best friend.

# Create

data = {"name": "image", "format": "png"}

# Access

data["name"]

# Add/Update

data["size"] = "1024x768"

# Loop

for key, value in data.items():

    print(key, value)

# Safe Access

data.get("missing_key", "default")Code language: PHP (php)

Start Using Cloudinary

Sign up for our free plan and start creating stunning visual experiences in minutes.

Sign Up for Free