Python Append to Dictionary Add Key Value Pair

Dec 28, 2023

2 mins read

Published in

When working with Python dictionaries, adding key/value pairs is a common operation. The dict data structure provides a straightforward method for achieving this using the update() method or simply by directly assigning a value to a new key.

Let’s explore both methods:

Method 1: Using update() method

1
2
3
4
5
6
7
8
# Example Dictionary
my_dict = {'name': 'John',  'age': 25,  'city': 'New York'}

# Adding a new key/value pair
my_dict. update({'occupation': 'Engineer'})

# Updated dictionary
print(my_dict)

In this example, the update() method is used to append a new key ('occupation') with its corresponding value ('Engineer') to the existing dictionary.

Method 2: Directly Assigning a New Key/Value Pair

1
2
3
4
5
6
7
8
# Example Dictionary
my_dict = {'name': 'John',  'age': 25,  'city': 'New York'}

# Adding a new key/value pair
my_dict['occupation'] = 'Engineer'

# Updated dictionary
print(my_dict)

Here, we achieve the same result by directly assigning the value to a new key in the dictionary. This method is concise and often preferred when adding a single key/value pair.

Real-World Use Cases

  1. User Input Handling:
1
2
3
user_info = {}
user_info['username'] = input('Enter your username: ')
user_info['email'] = input('Enter your email: ')
  1. Configurations:
1
2
config = {'debug_mode': True,  'log_level': 'INFO'}
config. update({'max_attempts': 3})

Best Practices

  • Error Handling: Ensure that the key you’re trying to add doesn’t already exist to prevent overwriting existing data.

  • Dynamic Key/Value Generation: Use variables to generate dynamic key names or values.

1
2
3
# Dynamic key generation
key_name = 'address'
my_dict[key_name] = '123 Main Street'

Appending key/value pairs to a dictionary in Python is a fundamental skill. Whether you choose the update() method or direct assignment depends on your specific use case and coding style. Remember to consider best practices to write clean, readable, and error-resistant code.

Sharing is caring!