Python updating dictionary with new keys

Brief about dictionary

In Python, a dictionary is a collection of key-value pairs. It is an unordered and mutable data type, which means that the items in a dictionary can be changed, and the order of the items is not guaranteed to be the same as the order in which they were added.

dictionary is defined by curly braces {} and key-value pairs are separated by colons. Here’s an example of how to create a dictionary in Python:

Python
my_dict = {'name': 'Ashraful', 'age': 23, 'city': 'New York'}

The keys in a dictionary must be unique and immutable, meaning they can’t be changed after they’re created. Common types of keys include strings, numbers, and tuples. The values in a dictionary can be any type of data, including other dictionaries.

You can access the values in a dictionary by using their keys, like this:

Python
print(my_dict['name'])  # Output: 'Ashraful'

You can also add, modify or delete key-value pairs in a dictionary using the following methods:

  • ‘my_dict[key]’ = value’: adds or modifies a key-value pair in the dictionary
  • ‘del my_dict[key]’: delet

Add new key in dictionary

To add a new key-value pair to a dictionary in Python, you can use the square bracket notation:

Python
# Creating an empty dictionary
dict1 = {}

# Adding a new key-value pair
dict1['name'] = 'Ashraful'
dict1['age'] = 23

print(dict1) # Output: {'name': 'Ashraful', 'age': 23}

You can also use the ‘update()‘ method to add multiple key-value pairs at once:

Python
# Creating an empty dictionary
dict1 = {}

# Adding multiple key-value pairs
dict1.update({'name': 'Ashraful Ahmed', 'age': 24})

print(dict1) # Output: {'name': 'Ashraful Ahmed', 'age': 24}

Update dictionary keys with replacing new keys

To replace a key in a dictionary in Python, you can create a new key-value pair with the new key and the old value, and then delete the old key-value pair. Here’s an example:

Python
# define a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}

# replace the key "banana" with "pear"
my_dict["pear"] = my_dict.pop("banana")

# print the updated dictionary
print(my_dict)

Output:

{'apple': 1, 'cherry': 3, 'pear': 2}

In this example, the ‘pop()‘ method is used to remove the key-value pair with the old key “banana” from the dictionary and return its value. This value is then assigned to a new key “pear” using dictionary assignment. The end result is that the key “banana” has been replaced with “pear” in the dictionary.

Note that if the old key does not exist in the dictionary, the ‘pop()‘ method will raise a ‘KeyError‘ exception. To avoid this, you can use the ‘get()‘ method instead:

Python
# define a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}

# replace the key "banana" with "pear", if "banana" exists
if "banana" in my_dict:
    my_dict["pear"] = my_dict.pop("banana")

# print the updated dictionary
print(my_dict)

Output:

{'apple': 1, 'cherry': 3, 'pear': 2}

In this example, the ‘if‘ statement is used to check if the old key “banana” exists in the dictionary before attempting to replace it. If the key does not exist, the code inside the ‘if‘ block is skipped.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.