w3resource

Python: Add a key to a dictionary


2. Add Key to Dictionary

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} 

For more Practice: Solve these Related Problems:

  • Write a Python script to add a new key-value pair to a dictionary only if the key does not exist already.
  • Write a Python script to update a dictionary with multiple new keys from a list, setting each to a default value.
  • Write a Python script to merge a list of key-value pairs into an existing dictionary without overwriting existing keys.
  • Write a Python script to insert a key into a dictionary at a specific position while preserving insertion order.

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.