Skip to content

How to add the same key value in dictionary Python | Example code

  • by

Python Dictionary does not support the same name keys. You can’t use the same key multiple times because the Python dictionary must be unique. However, you can use the list to add the same key for multiple values in dictionary Python.

Where more than one value can correspond to a single key using a list in a Python dictionary.

For example, with the dictionary {"x": [1, 2]}, 1 and 2 are both connected to the key "x" and can be accessed individually.

Here’s how you can add or update a key-value pair in a dictionary:

# Initialize a dictionary
my_dict = {}

# Adding key-value pairs
my_dict['key1'] = 'value1'
my_dict['key2'] = 'value2'

# Updating a key's value
my_dict['key1'] = 'new_value1'  # This will overwrite the old value for 'key1'

print(my_dict)

If you want to have multiple values associated with the same key, you can use a list or another data structure as the value. For example:

my_dict = {}

# Adding multiple values to the same key using a list
my_dict['key1'] = ['value1', 'value2']
my_dict['key2'] = ['value3']

# Adding another value to an existing key
my_dict['key1'].append('value4')

print(my_dict)

Read the official doc: documentation:

Example add the same key value in the dictionary Python

Simple example code how to use a list in a dictionary to associate more than one value with a key and add a value to an existing key.

my_dict = {"a": [1, 2], "b": [3, 4]}

print(my_dict)

my_dict["b"].append(5)

print(my_dict)

Output:

How to add the same key value in dictionary Python

Comment if you have any doubts or suggestions on this Python dictionary example.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *