CodeBlanks Logo Icon CodeBlanks

Dict basics

Learn key-value mapping with {k: v}.

Dict basics

A dict (dictionary) is an ordered collection of key-value pairs. It uses curly braces and a colon:

person = {"name": "Alex", "age": 28}
print(person["name"])  # Alex

A dict maps a key to a value. Keys must be unique; values can be any type. Access is done by key indexing.

Since Python 3.7, a dict keeps its insertion order. This makes loop order stable.

Dict access and assignment

Adding a new key to a dict is done by assignment; querying a missing key raises KeyError:

person = {"name": "Alex"}
person["age"] = 28      # adds a new key
print(person["age"])   # 28
print(person["city"])  # KeyError

To return a default for missing keys, use .get(); this method is safe.

Practice Print dict elements

Assign the dict {"name": "Ayse", "age": 28} to person. Assign person["name"] to name and person["age"] to age. Then print print(name, age).

Starter code

main.py
# Define a person with a dict

Sample solution

main.py
person = {"name": "Ayse", "age": 28}
name = person["name"]
age = person["age"]
print(name, age)

Expected output

Ayse 28

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a valid dict?

  • {"a": 1} Correct answer
  • ("a": 1)
  • <"a": 1>
  • ["a": 1]

Explanation: {"a": 1} with curly braces is a dict.

2 Match the dict concepts

Term Meaning
{"k": v} Dict syntax
key Key
value Value
person["name"] Access

3 Access a dict element

Question
person = {"name": "Ayse"}
print(person[____])
Answer
person = {"name": "Ayse"}
print(person["name"])

Explanation: person["name"] gives the value.

All lessons in Beginner