Last updated

Python Dictionaries

Definition: A dictionary stores data as key:value pairs. Instead of looking values up by position (like a list), you look them up by a meaningful name (the key). Written with curly braces { }.

person = {
  "name": "Sam",
  "age": 25,
  "city": "London"
}
print(person)

Example 1 — getting a value by key

print(person["name"])   # Sam
print(person["age"])    # 25

Example 2 — adding and changing

person["email"] = "sam@mail.com"   # add a new pair
person["age"] = 26                 # change an existing value
print(person)

Example 3 — looping through pairs

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

Example 4 — handy methods

print(person.keys())      # all keys
print(person.values())    # all values
print(person.get("name")) # safe way to read a key

💡 When to use: a dictionary is perfect for one "thing" with named properties — a user, a product, a config. Use a list when order and position matter; use a dict when names matter.

Try it Yourself
Output

          
Ad · responsive