Working with DataCore· 35 min read

Dictionaries

Store data as key–value pairs — perfect for describing one thing.

What you will learn

  • Create dictionaries
  • Read and change values
  • Loop a dictionary

Key–value pairs

A dictionary stores data as key–value pairs, written inside curly braces { }. Think of it as a labelled box: instead of looking things up by position (like a list), you look them up by a key — a name you choose. It is perfect for describing one thing that has several named details.

A dictionary describes one thing
user = {
    "name": "Asha",
    "age": 22,
    "city": "Lucknow"
}
print(user["name"])     # Asha
user["age"] = 23        # change a value
user["email"] = "a@x.com"   # add a new key

The user dictionary holds three pairs — for example the key "name" points to the value "Asha". To read a value you put its key in square brackets: user["name"] gives Asha. To change a value, assign to that key: user["age"] = 23 replaces 22 with 23. And assigning to a key that does not exist yet adds it — that is how "email" joins the dictionary.

Note: Output: Asha (Only the print line shows output; the other two lines quietly change and add values.)

Loop a dictionary

To go through every pair in a dictionary, loop over .items(), which hands you the key and value together on each pass.

Loop keys and values
for key, value in user.items():
    print(key, "=", value)

On each turn of the loop, key becomes the next key and value becomes its value, so the line prints each pair like name = Asha. This runs once for every pair in the dictionary.

Note: Output: name = Asha age = 23 city = Lucknow email = a@x.com (Remember we changed age to 23 and added email above.)

Note: Dictionaries look just like JSON (JavaScript Object Notation — a common text format for sending data between programs) and database rows — this is the shape of real-world data you’ll use in Django and data science.

Q. How do you read the value for key "name" in a dict called user?

Answer: Use square brackets with the key: user["name"].

✍️ Practice

  1. Make a dictionary describing yourself and print two values.
  2. Loop a dictionary and print each key and value.

🏠 Homework

  1. Make a list of 3 product dictionaries (name, price) and loop to print them.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →