Dictionaries in Python

Dictionaries are data structures used to map arbitrary keys to values.

Note:

  • Lists can be thought of as dictionaries with integer keys within a certain range.
  • Dictionaries can be indexed in the same way as lists, using square brackets containing keys.
  • Each element in a dictionary is represented by a key:value pair.
  • A dictionary can store any types of data as values.
  • An empty dictionary is defined as {}.

Example:

price = {"Honda": 2000, "Yamaha": 1900, "Suzuki": 1500}
print(price["Honda"])
print(price["Suzuki"])

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
2000
1500
ddn_ro@linux:~/Desktop$

A KeyError is returned when trying to index a key that doesn’t exist in the dictionary.

Example:

price = {"Honda": 2000, "Yamaha": 1900, "Suzuki": 1500}
print(price["Honda"])
print(price["Piaggio"])

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
2000
Traceback (most recent call last):
  File "file.py", line 3, in 
    print(price["Piaggio"])
KeyError: 'Piaggio'
ddn_ro@linux:~/Desktop$

Note:
Only immutable objects can be used as keys to dictionaries. Immutable objects are those that can’t be changed. Trying to use a mutable object as a dictionary key causes a TypeError.

bad_dictionary = {
[1, 2, 3]: "one two three", 
}

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
Traceback (most recent call last):
  File "file.py", line 2, in 
    [1, 2, 3]: "one two three", 
TypeError: unhashable type: 'list'
ddn_ro@linux:~/Desktop$

Leave a Reply