w3resource

Python: Add a key to a dictionary

Python dictionary: Exercise-2 with Solution

Write a Python program to add a key to a dictionary.

Sample Solution:

Python Code:

# Create a dictionary 'd' with two key-value pairs.
d = {0: 10, 1: 20}

# Print the original dictionary 'd'.
print(d)

# Update the dictionary 'd' by adding a new key-value pair {2: 30}.
d.update({2: 30})

# Print the dictionary 'd' after the update, which now includes the new key-value pair.
print(d) 

Sample Output:

{0: 10, 1: 20}                                                                                                
{0: 10, 1: 20, 2: 30} 

Python Code Editor:

Previous: Write a Python program to sort (ascending and descending) a dictionary by value.
Next: Write a Python program to concatenate following dictionaries to create a new one.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.