Dictionaries and Other Collections · practice
Add and Change Dictionary Entries
Change an existing value
Start with a small record:
profile = {
"name": "Mina",
"city": "Lisbon",
}
Assign through the existing "city" key:
profile["city"] = "Porto"
The key already exists, so its
print(profile)
# {'name': 'Mina', 'city': 'Porto'}
The dictionary does not gain a second "city" entry. Keys are unique.
Add a new key-value pair
Use the same syntax with a key that is not present:
profile["language"] = "Portuguese"
Now the dictionary has three entries:
{
"name": "Mina",
"city": "Porto",
"language": "Portuguese",
}
The syntax is identical. Whether it adds or changes depends on whether the key already exists.
Count entries with len()
len() reports how many key-value pairs a dictionary contains:
print(len(profile))
# 3
It does not count the characters in the keys or values.
Order is not the identity
Modern Python remembers insertion order when it displays or
These dictionaries compare equal:
first = {"name": "Mina", "city": "Porto"}
second = {"city": "Porto", "name": "Mina"}
print(first == second)
# True
They hold the same key-value pairs, so their different insertion order does not make them different records.
What is the value of len(item) at the end?
item = {"name": "Map", "price": 4}
item["price"] = 5
item["stock"] = 12
print(len(item))
Task
Update the existing profile
Change
"city"from"Lisbon"to"Porto".Add a new key
"language"with the"Portuguese".Keep the given report lines.
Expected output:
Mina lives in Porto.
Language: Portuguese
Fields: 3