Unordered collection of items.
Every dictionary item is a Key-value pair.
Creating a Dictionary
Created by enclosing items within {curly} brackets
Each item in dictionary has a key - value pair separated by a comma.
Code
Key - Value Pairs
Code
In the above dictionary, the
- keys are nameandage
- values are Tejaand15
Collection of Key-Value Pairs
Code
Output
Immutable Keys
Keys must be of immutable type and must be unique.
Values can be of any data type and can repeat.
Code
Creating Empty Dictionary
Code - 1
Output
Code - 2
Output
Accessing Items
To access the items in dictionary, we use square bracket
Code
Output
Accessing Items - Get
The
Code
Output
Code
Output
KeyError
When we use the square brackets
Code
Output
Membership Check
Checks if the given key exists.
Code
Output
Operations on Dictionaries
We can update a dictionary by
- Adding a key-value pair
- Modifying existing items
- Deleting existing items
Adding a Key-Value Pair
Code
Output
Modifying an Existing Item
As dictionaries are mutable, we can modify the values of the keys.
Code
Output
Deleting an Existing Item
We can also use the
Code
Output
Dictionary Views
They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.
Dictionary Methods
- dict.keys()
- returns dictionary Keys
- dict.values()
- returns dictionary Values
- dict.items()
- returns dictionary items(key-value) pairs
The objects returned by
Getting Keys
The
Code
Output
Getting Values
The
Code
Output
Getting Items
The
Code
Output
Iterate over Dictionary Views
Example - 1
Code
Output
Example - 2
Code
Output
Example - 3
Code
Output
Example - 4
Code
Output
Dictionary View Objects
Code
Output
Converting to Dictionary
Code
Output
Code
Output
Type of Keys
A dictionary key must be of a type that is immutable.