02 CDT - 07 Dictinaries
A dictionary in Python is a collection of key-value pairs. Each key is connected to a specific value, and you can use the key to access its corresponding value.
Structure of a Dictionary
An empty dictionary is created like this:
students = {}
- A dictionary is written within curly braces
{}
. - Each key is connected to its value by a colon
:
. - Each key-value pair is separated by a comma
,
.
a = {"colour": "green", "points": 5}
This dictionary has:
- Key:
"colour"
with its Value:"green"
. - Key:
"points"
with its Value:5
.
students = {"name": "Alice", "age": 22, "major": "Computer Science"}
The key is used to retrieve the corresponding value.
Dictionary like a real-life word dictionary, where words (keys) are associated with their meanings (values).
In programming, dictionaries are useful when there is a need to map values together, which is often more practical than using multiple lists separately.
Difference Between Lists and Dictionaries
- Lists are indexed by numbers (i.e., positions), and the values can be accessed using these indices.
lst = [13, 24, 54, 77, 33]
Here, the positions 0, 1, 2, 3, 4
are used as indices to access corresponding values in the list. The access is only through range(0, n)
.
- Dictionaries, on the other hand, allow you to use actual words (keys) as indices. This makes dictionaries more flexible than lists, especially when you need to associate specific keys with values.
Starting from Python 3.7, dictionaries maintain the order of insertion. This means that when you iterate over the keys of a dictionary, they will appear in the order in which they were added.
Key Characteristics of Dictionary Keys and Values
- Keys:
- Keys in a dictionary must be unique. If you add a key that already exists, the old value will be overwritten by the new one.
- Keys must be immutable, meaning they cannot be lists, dictionaries, or other mutable types. Valid key types are:
- int, float, bool, string, tuple.
- Values:
- Values in a dictionary can be of any data type.
- Values can also be repeated, unlike keys.
Crating a dictionary with Key-Value Pairs
To add a new key-value pair to an existing dictionary, simply reference the dictionary by its name, then specify the new key inside square brackets []
and assign the value to it.
>>> test ={}
>>> test['Dhawan'] = 84
>>> test['Pujara'] = 16
>>> test
{'Dhawan': 84, 'Pujara': 16}
>>> test['Dhawan'] = 99
>>> test
{'Dhawan': 99, 'Pujara': 16}
'Dhawan'
and 'Pujara'
are the keys, and 84
and 16
are their corresponding values. The repeated value Dhawan
got over written.
>>> a = {}
>>> a["x"] = 0
>>> a["y"] = 25
>>> a
{'x': 0, 'y': 25}
>>> a = {"colour": "green", "points": 5 }
>>> a["x"] = 0
>>> a["y"] = 25
>>> a
{'colour': 'green', 'points': 5, 'x': 0, 'y': 25}
Nesting in Dictionaries
Nested Dictionaries
You can create nested dictionaries, which means a dictionary inside another dictionary. This allows you to represent more complex data structures where keys can themselves have dictionaries as values.
>>> score = {}
>>> score["Test1"] = {}
>>> score["Test2"] = {}
# there can be multiple keys for a given value
>>> score["Test1"]["Dhawan"] = 84
>>> score["Test1"]["Kohli"] = 200
>>> score["Test2"]["Dhawan"] = 50
>>> score
{'Test1': {'Dhawan': 84, 'Kohli': 200}, 'Test2': {'Dhawan': 50}}
Nesting Dictionaries in Lists
You can also store multiple dictionaries inside a list. This can be useful for grouping several dictionaries together in a collection.
>>> test1 = {}
>>> test2 = {}
>>> test3 = {}
>>> score = [test1, test2, test3]
>>> score
[{}, {}, {}]
>>> type(score)
<class 'list'>
Nested Dictionaries with Dictionary Keys
We can store dictionaries within other dictionaries using string keys. However, remember that dictionaries themselves are mutable and unhashable, so you cannot use a dictionary as a key in another dictionary.
# Error because no key was given
>>> score = {test1, test2, test3 }
TypeError: unhashable type: 'dict'
# Key cannot be Dictionary
>>> score = {"test1": test1, "test2": test2, "test3": test3 }
>>> score
{'test1': {}, 'test2': {}, 'test3': {}}
>>> type(score)
<class 'dict'>
Accessing Values through Key Indexing
Unlike lists, dictionaries don’t use numeric indexing. Instead, you access the values by using the key.
To access a value in a dictionary, we use the key inside square brackets ([]
).
Nested Values of dictionary can be accessed by chain indexing.
>>> score["Test2"]
{'Dhawan': 50}
>>> score["Test1"]
{'Dhawan': 84, 'Kohli': 200}
>>> score["Test1"]["Kohli"]
200
>>> score["Test2"]["Dhawan"]
50
- Indexing with numbers will not work with dictionaries. Specific key must be used to access values.
Checking for Key Existence
The in
or not in
membership operators are used to check whether a specific key exists in a dictionary or not.
These operators return True
if the key is present and False
if it is not.
>>> score = {'Test1': {'Dhawan': 84, 'Kohli': 200}, 'Test2': {'Dhawan': 50}}
>>> "Dhawan" in score
False
>>> "Kohli" in score
False
>>> "Dhawan" in score["Test1"]
True
>>> "Dhawan" not in score["Test1"]
False
>>> "Kohli" in score["Test1"]
True
>>> "Kohli" in score["Test2"]
False
in
checks whether a key exists in the dictionary.
"Dhawan" in score
returnsFalse
because"Dhawan"
is not a direct key inscore
."Dhawan" in score["Test1"]
returnsTrue
because"Dhawan"
is a key inside the nested dictionary for"Test1"
.