DEV Community

Vasanthakumari N
Vasanthakumari N

Posted on

Python Day 29: Dictionary Operations and Methods

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)
Enter fullscreen mode Exit fullscreen mode
Output:

{'jack': 4098, 'sape': 4139, 'guido': 4127}
{'jack': 4098, 'sape': 4139, 'guido': 4127}
{'jack': 4098, 'sape': 4139, 'guido': 4199}
Enter fullscreen mode Exit fullscreen mode

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'])
Enter fullscreen mode Exit fullscreen mode

Output:

4098
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode
Output:

{'jack': 4098, 'irv': 4127}
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode
Output:

['jack', 'sape', 'guido']
Enter fullscreen mode Exit fullscreen mode

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))

Enter fullscreen mode Exit fullscreen mode
Output:

['guido', 'jack', 'sape']
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode
Output:

{'name': 'raja', 'exp': 5, 'city': 'chennai'}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode
Output:

raja
{'name': 'bala', 'exp': 5, 'city': 'chennai'}

Enter fullscreen mode Exit fullscreen mode

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'))
Enter fullscreen mode Exit fullscreen mode

Output:

None
Enter fullscreen mode Exit fullscreen mode

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'))
Enter fullscreen mode Exit fullscreen mode
Output:

Data is not present
Enter fullscreen mode Exit fullscreen mode

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())
Enter fullscreen mode Exit fullscreen mode
Output:

dict_keys(['idli', 'dosai', 'poori'])
dict_values([20, 30, 35])
dict_items([('idli', 20), ('dosai', 30), ('poori', 35)])

Enter fullscreen mode Exit fullscreen mode

We can convert these results into lists using list().


print(list(food_items.keys()))
print(list(food_items.values()))
print(list(food_items.items()))
Enter fullscreen mode Exit fullscreen mode
Output:

['idli', 'dosai', 'poori']
[20, 30, 35]
[('idli', 20), ('dosai', 30), ('poori', 35)]
Enter fullscreen mode Exit fullscreen mode

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])
Enter fullscreen mode Exit fullscreen mode
Output:

30
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

20
30
35
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

dosai
Enter fullscreen mode Exit fullscreen mode

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'))
Enter fullscreen mode Exit fullscreen mode
Output:

Data is not present
None
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

apple 100
The value is 100
Key starts with a vowel: 100
banana 80
grapes 70
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode
Output:

{'apple': 110.0, 'banana': 88.0, 'grapes': 77.0}

Enter fullscreen mode Exit fullscreen mode

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)