Dictionaries
Sequences find things by position: item 0, item 1, item 2. But if I hand you a student record, you do not want “item 1” — you want the marks. A dictionary lets you ask for exactly that, by name.
1A key, and its value
A dictionary is written in curly braces { }. Inside it are pairs. Each pair is a key, then a colon, then its value, and the pairs are separated by commas.
student = {'name': 'Ramesh', 'marks': 87}
print(student){'name': 'Ramesh', 'marks': 87}It works like a real dictionary. You look up a word (the key) to find its meaning (the value). You would never look up “the 400th word” — and in a Python dictionary you cannot.
2Looking a value up
Square brackets again — but with a key inside them, not a position. Click the keys below.
dictionary[key] gives you the value behind that key. There is no position 0 in a dictionary, and asking for one is meaningless. Ask for a key that does not exist and Python stops with a KeyError.3The rules for keys
Two students can score 87, so values may repeat happily. But each key appears once — otherwise, when you asked for it, Python would not know which one you meant.
Exactly the word from the last lesson. A string, a number or a tuple may be a key, because none of them can change. A list may not — and neither may a dictionary.
The second rule is the reason the last lesson came first. A key has to stay still: Python files each pair away under its key, and if a key could change afterwards, the pair would be filed under something that no longer exists and you could never find it again. So Python refuses at the moment you try:
scores = {'ramesh': 87, 101: 'roll number', (10, 20): 'a point'}
print(scores) # string, number and tuple keys are all fine
marks = {['ramesh', 'kumar']: 87} # a list cannot be a key{'ramesh': 87, 101: 'roll number', (10, 20): 'a point'}
Traceback (most recent call last):
File "key_rules.py", line 4, in <module>
marks = {['ramesh', 'kumar']: 87} # a list cannot be a key
^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'list'Read the immutable column from the last lesson and you have the list of things that may be a key. Read the mutable column and you have the list of things that may not.
The first rule has no error message at all, which makes it worth seeing. Write the same key twice and Python does not complain — it simply keeps the last one, because there was never room for two:
marks = {'asha': 1, 'bilal': 2, 'asha': 9}
print(marks){'asha': 9, 'bilal': 2}One 'asha' row, holding 9. The 1 was not merged or added to — it was quietly replaced, and nothing warned you.
4Useful things to do with one
student = {'name': 'Ramesh', 'marks': 87}
print(len(student))
print('marks' in student)
print('age' in student)2 True False
len() counts the pairs, not the individual keys and values — two pairs here, so 2. And in checks the keys, not the values.
A dictionary also has methods to hand you its parts: keys() for the keys alone, values() for the values alone, and items() for both together.
student = {'name': 'Ramesh', 'marks': 87}
print(student.keys())
print(student.values())dict_keys(['name', 'marks']) dict_values(['Ramesh', 87])
5A dictionary can be changed
Like a list, and unlike a string or a tuple, a dictionary can be edited. Point at a key and give it a new value:
student = {'name': 'Ramesh', 'marks': 87}
student['marks'] = 90
print(student){'name': 'Ramesh', 'marks': 90}No error, and the printed dictionary shows why: the marks behind 'marks' went from 87 to 90, in place. A dictionary is mutable, in the exact sense the last lesson gave that word — which is also why a dictionary may never be used as a key.
6Try it at the prompt
7Recap
{ }. You fetch a value with d[key], never by position. Keys must be unique. A missing key gives a KeyError. And a dictionary can be changed.What does {'name': 'Ramesh', 'marks': 87}['marks'] give?
What is len({'name': 'Ramesh', 'marks': 87})?
You ask a dictionary for a key it does not have. What happens?