Python Dictionaries and Their Usage
ChatGPT

Python Dictionaries and Their Usage

Work with data using key-value pairs.

What is a dictionary?

A dictionary in Python is an unordered collection of key-value pairs. Unlike lists, where you access items by position (index), dictionaries let you access values using unique keys.

Think of a dictionary like a real-life lookup table:

  • A key is the identifier
  • A value is the data associated with that key


Creating a dictionary

person = {
    "name": "Alice",
    "age": 30,
    "city": "Prague"
}        

Accessing values by key

print(person["name"])  # Output: Alice
print(person["age"])   # Output: 30        
If the key doesn’t exist, Python raises a KeyError.

Using get() – safer access

print(person.get("email"))         # Output: None
print(person.get("email", "N/A"))  # Output: N/A        

Looping through a dictionary

for key in person:
    print(key, ":", person[key])        

Or using items() for cleaner key-value access:

for key, value in person.items():
    print(f"{key}: {value}")        

Useful dictionary methods

keys() – get all keys

print(person.keys())        

values() – get all values

print(person.values())        

items() – list of (key, value) pairs

print(person.items())        

update() – update or add items

person.update({"age": 31})
person["email"] = "alice@example.com"        

pop() – remove item by key

person.pop("city")        

clear() – remove all items

person.clear()        

Dictionaries inside lists and nested structures

Python allows complex data structures, like lists of dictionaries:

people = [
    {"name": "Tom", "age": 25},
    {"name": "Eva", "age": 28}
]

for person in people:
    print(person["name"])        

Summary

  • A dictionary is a collection of key-value pairs
  • Keys must be unique, values can be of any type
  • Accessing values is fast and intuitive
  • Methods like get(), items(), update(), and pop() are powerful tools
  • Dictionaries are widely used in APIs, config files, data parsing, and web apps

To view or add a comment, sign in

More articles by Štefan Tusjak

Insights from the community

Others also viewed

Explore topics