A dictionary is a collection of key-value pairs. It allows us to store related information together and access values using their keys.
1. What is a Dictionary?
A dictionary is a data structure that stores data in the form of key-value pairs.
Each pair contains:
- Key: Used to identify or access a value.
- Value: The data associated with the key.
Example:
d = {"dhoni": 90, "virat": 108}
print(d["dhoni"])
Output:
90
Here:
- "dhoni" is the key.
- 90 is the value.
- "virat" is the key.
- 108 is the value.
We can access the value directly using its corresponding key.
2. Dictionary Properties
| Feature | Description |
|---|---|
| Collection | Stores data as key-value pairs |
| Keys | Must be unique |
| Values | Duplicates are allowed |
| Key Types | Must be hashable |
| Value Types | Can be any data type |
| Mutable | Elements can be added, updated, and deleted |
| Ordered | Maintains insertion order (Python 3.7+) |
| Indexing | Does not support positional indexing |
| Slicing | Does not support slicing |
| Access | Values are accessed using keys |
| Data Structure | Also known as an associative array or mapping |
3. Dictionary Syntax
A dictionary is created using curly braces {}.
d = {
"dhoni": 90,
"virat": 67,
"rohit": 91
}
print(d)
Output:
{'dhoni': 90, 'virat': 67, 'rohit': 91}
Important points:
- Keys and values are separated by a colon (:).
- Each key-value pair is separated by a comma.
- Curly braces {} are used to create a dictionary.
- An empty dictionary can be created using {}.
Example:
d = {}
print(type(d))
Output:
<class 'dict'>
4. Keys and Values
Keys
- Keys must be unique.
- Keys must be hashable.
- Strings, numbers, and immutable tuples (containing only hashable elements) can be used as keys.
- Lists, sets, and dictionaries cannot be used as keys because they are mutable and unhashable.
Values
- Values can be duplicated.
- Values can be of any data type.
- Values can be strings, numbers, lists, tuples, sets, or even dictionaries.
Example:
d = {
"name": "Dhoni",
"age": 43,
"marks": [90, 85, 95],
"subjects": {"Python", "Java"}
}
print(d)
5. Accessing Dictionary Values
We can access dictionary values using their keys.
scoreboard = {
"dhoni": 90,
"virat": 67,
"rohit": 91
}
print(scoreboard["dhoni"])
print(scoreboard["virat"])
print(scoreboard["rohit"])
Output:
90
67
91
If we try to access a key that does not exist, Python raises a KeyError.
Example:
print(scoreboard["Mohammed"])
Output:
KeyError: 'Mohammed'
We can use the get() method to avoid this error.
print(scoreboard.get("Mohammed"))
Output:
None
6. Adding and Updating Dictionary Elements
Dictionaries are mutable, so we can add new key-value pairs and update existing values.
Adding a new element
scoreboard = {
"dhoni": 90,
"virat": 67
}
scoreboard["rohit"] = 91
print(scoreboard)
Output:
{'dhoni': 90, 'virat': 67, 'rohit': 91}
Updating an existing element
scoreboard = {
"dhoni": 90,
"virat": 67
}
scoreboard["dhoni"] = 100
print(scoreboard)
Output:
{'dhoni': 100, 'virat': 67}
Remember:
- If the key already exists, its value gets updated.
- If the key does not exist, a new key-value pair is added.
7. Dictionary vs Set
Both dictionaries and sets use curly braces, but their purposes are different.
Dictionary
scoreboard = {"dhoni": 90, "virat": 67}
Set
names = {"dhoni", "virat", "rohit"}
Example:
names = {"dhoni", "virat", "rohit"}
print(names["dhoni"])
Output:
TypeError
8. Dictionary with List as a Value
A dictionary can store lists as values.
This is useful when we want to store multiple values for a single key.
Example:
marks_dict = {}
marks_dict["Ramesh"] = [98, 97, 100, 89, 54]
marks_dict["Suresh"] = [58, 67, 90, 89, 54]
print(marks_dict)
Output:
{
'Ramesh': [98, 97, 100, 89, 54],
'Suresh': [58, 67, 90, 89, 54]
}
Here:
- "Ramesh" is a key.
- [98, 97, 100, 89, 54] is its value.
- "Suresh" is another key.
- [58, 67, 90, 89, 54] is its value.
Accessing List Elements Through Dictionary Keys
for mark in marks_dict["Ramesh"]:
print(mark, end=' ')
Output:
98 97 100 89 54
Here, we first access the list using the dictionary key "Ramesh", and then iterate through the list using a for loop.
A set does not support indexing or accessing elements using keys.
Top comments (0)