1. Adding and Updating Dictionary Items
We can add a new key-value pair by assigning a value to a new key.
If the key already exists, Python updates its value instead of creating a duplicate key.
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print(tel)
tel['guido'] = 4127
print(tel)
tel['guido'] = 4199
print(tel)
Output:
{'jack': 4098, 'sape': 4139, 'guido': 4127}
{'jack': 4098, 'sape': 4139, 'guido': 4127}
{'jack': 4098, 'sape': 4139, 'guido': 4199}
Important points:
- A new key creates a new dictionary item.
- Assigning a value to an existing key updates that value.
- Duplicate keys are not maintained in a dictionary.
2. Accessing Dictionary Values
We can access a dictionary value using its key.
tel = {'jack': 4098, 'sape': 4139}
print(tel['jack'])
Output:
4098
If the requested key does not exist, accessing it with square brackets raises a KeyError.
3. Deleting Dictionary Items
The del keyword is used to delete an item from a dictionary.
tel = {'jack': 4098, 'sape': 4139}
del tel['sape']
tel['irv'] = 4127
print(tel)
Output:
{'jack': 4098, 'irv': 4127}
Here:
- del tel['sape'] removes the key sape and its value.
- tel['irv'] = 4127 adds a new item.
4. Converting Dictionary Keys into a List
When we pass a dictionary to the list() function, Python returns a list containing its keys.
tel = {'jack': 4098, 'sape': 4139, 'guido': 4127}
print(list(tel))
Output:
['jack', 'sape', 'guido']
5. Sorting Dictionary Keys
The sorted() function returns a new list containing the dictionary keys in sorted order.
tel = {'jack': 4098, 'sape': 4139, 'guido': 4127}
print(sorted(tel))
Output:
['guido', 'jack', 'sape']
Remember: sorted() does not modify the original dictionary. It returns a sorted list of keys by default.
6. Creating an Empty Dictionary
We can create an empty dictionary using curly braces {} or the dict() function.
empty_dict = {}
print(empty_dict)
Output:
{}
7. Creating a Dictionary with Data
We can store different types of information in a dictionary using key-value pairs.
employee = {
'name': 'raja',
'exp': 5,
'city': 'chennai'
}
print(employee)
Output:
{'name': 'raja', 'exp': 5, 'city': 'chennai'}
Here:
- name is a key, and raja is its value.
- exp is a key, and 5 is its value.
- city is a key, and chennai is its value.
8. Accessing and Updating Dictionary Values
We can access a value using its key and update it by assigning a new value.
employee = {'name': 'raja', 'exp': 5, 'city': 'chennai'}
print(employee['name'])
employee['name'] = 'bala'
print(employee)
Output:
raja
{'name': 'bala', 'exp': 5, 'city': 'chennai'}
The existing value raja is replaced with bala.
9. Using the get() Method
If we try to access a key that does not exist using square brackets, Python raises a KeyError.
To avoid this, we can use the get() method.
employee = {'name': 'raja', 'exp': 5, 'city': 'chennai'}
print(employee.get('age'))
Output:
None
The get() method returns None when the key is not available.
We can also provide a default value.
print(employee.get('age', 'Data is not present'))
Output:
Data is not present
10. Dictionary Methods: keys(), values(), and items()
Python provides three useful methods to retrieve dictionary information.
Let's understand them using an example.
food_items = {
"idli": 20,
"dosai": 30,
"poori": 35
}
print(food_items.keys())
print(food_items.values())
print(food_items.items())
Output:
dict_keys(['idli', 'dosai', 'poori'])
dict_values([20, 30, 35])
dict_items([('idli', 20), ('dosai', 30), ('poori', 35)])
We can convert these results into lists using list().
print(list(food_items.keys()))
print(list(food_items.values()))
print(list(food_items.items()))
Output:
['idli', 'dosai', 'poori']
[20, 30, 35]
[('idli', 20), ('dosai', 30), ('poori', 35)]
11. Iterating Through Dictionary Keys
We can use a for loop with the keys() method to iterate through dictionary keys.
food_items = {"idli": 20, "dosai": 30, "poori": 35}
for food_name in food_items.keys():
if food_name == 'dosai':
print(food_items[food_name])
Output:
30
Here, the loop checks each food name. When the key is dosai, it accesses and prints its value.
12. Iterating Through Dictionary Values
We can use the values() method to access all dictionary values.
food_items = {"idli": 20, "dosai": 30, "poori": 35}
for food_price in food_items.values():
print(food_price)
Output:
20
30
35
Here, the loop directly accesses the values without using their keys.
13. Iterating Through Keys and Values Using items()
The items() method returns both keys and values as pairs.
We can use two variables in the for loop to access them separately.
food_items = {"idli": 20, "dosai": 30, "poori": 35}
for k, v in food_items.items():
if v == 30:
print(k)
Output:
dosai
Here:
- k represents the key.
- v represents the value.
- When the value is 30, the corresponding key is printed.
14. Using get() with a Default Message
We can use get() to check whether a particular key is available and display a custom message if it is missing.
food_items = {"idli": 20, "dosai": 30, "poori": 35}
print(food_items.get('empId', 'Data is not present'))
print(food_items.get('empId'))
Output:
Data is not present
None
Since empId does not exist:
- The first statement returns the default message.
- The second statement returns None.
15. Applying Conditions While Iterating Through a Dictionary
We can use conditional statements inside a for loop to filter dictionary data.
fruits_dict = {
'apple': 100,
'banana': 80,
'grapes': 70
}
for k, v in fruits_dict.items():
print(k, v)
if len(k) == 5:
print("The value is", v)
if k[0].lower() in 'aeiou':
print("Key starts with a vowel:", v)
Output:
apple 100
The value is 100
Key starts with a vowel: 100
banana 80
grapes 70
Let's understand the conditions:
Condition 1: len(k) == 5
- len(k) returns the number of characters in the key.
- If the key contains exactly five characters, its value is printed.
Condition 2: k[0].lower() in 'aeiou'
- k[0] accesses the first character of the key.
- lower() converts it into lowercase.
- in 'aeiou' checks whether the first character is a vowel.
For apple, the first character is a, so its value is printed.
16. Updating Dictionary Values Using a Loop
We can update all dictionary values by iterating through the keys.
Let's increase every fruit price by 10%.
fruits_dict = {
'apple': 100,
'banana': 80,
'grapes': 70
}
for k in fruits_dict:
fruits_dict[k] += fruits_dict[k] * 0.1
print(fruits_dict)
Output:
{'apple': 110.0, 'banana': 88.0, 'grapes': 77.0}
Here:
- for k in fruits_dict iterates through dictionary keys.
- fruits_dict[k] accesses the value of the current key.
- fruits_dict[k] * 0.1 calculates 10% of the value.
- += adds the calculated amount to the existing value.
Top comments (0)