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.

Read official doc: documentation:

Example add the same key value in 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

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

Note: IDE: PyCharm 2021.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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.