Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.4 — Dictionaries: Look Things Up by Key
Python · Example 2 of 3

A chat conversation is a list of dictionaries

dict(zip(names, numbers)) pairs up two lists item by item (zip is Topic 2.6) and builds a dictionary from the pairs.

A dictionary stores pairs: each key leads to a value, and you look a value up by its key instead of by position. Dictionaries keep the order in which keys were added (guaranteed since Python 3.7) and are the shape of almost all JSON data.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Make a dictionary student = {"name": "Asha", "age": 21}. Add "city": "Delhi", change age to 22, then print every key and value as key: value.

02

Given marks = {"maths": 80, "science": 90}, print the mark for "english" as 0 if it is missing, without raising an error.

03

Count how many times each word appears in "to be or not to be" and print the dictionary.

Explain it without notes

01

How is a dictionary different from a list, and when do you use each?

02

What is the difference between d[key] and d.get(key)?

03

Does a dictionary keep order? Since which version?

04

How do you loop over the keys and values of a dictionary together?

05

What are the ways to merge two dictionaries, and what does "the right-hand value wins" mean for nested dictionaries?

A chat conversation is a list of dictionaries
Sign in to run this example in your browser.

Expected output

system -> You are a patient teacher.
user -> What is a dictionary?
assistant -> A dictionary maps keys to values.
last message: A dictionary maps keys to values.
from zip: {'a': 1, 'b': 2, 'c': 3}
letter counts: {'b': 1, 'a': 3, 'n': 2}