I want to add multiple values to a specific key in a python dictionary. How can I do that?
a = {} a["abc"] = 1 a["abc"] = 2
This will replace the value of a["abc"] from 1 to 2.
What I want instead is for a["abc"] to have multiple values(both 1 and 2).
By using the dictionary. update() function, we can easily append the multiple values in the existing dictionary. In Python, the dictionary. update() method will help the user to update the dictionary elements or if it is not present in the dictionary then it will insert the key-value pair.
We can add / append new key-value pairs to a dictionary using update() function and [] operator. We can also append new values to existing values for a key or replace the values of existing keys using the same subscript operator and update() function.
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
Can a Dictionary Have the Same Key in Python? Answer: No, it cannot have the same key in Python. If you attempt to add the same key, it overrides the previous key with the new value. However, you can add multiple values to one key using the list in item values.
The short answer is: use the update() function of Python to Add single or multiple elements to the Dictionary. You can also use the update() to change or replace the old value of the existing keys of Dictionary.
Python dictionary append multiple key-values 1 Python dict Append Multiple key-values#N#Python dictionary update () method takes a sequence as an argument, it can be,... 2 Append a list of values to an existing key More ...
In the above code, we have created a dictionary named ‘new_dictionary’ that contains elements in the form of key-value pairs. In this example, we have assigned multiple values with each key. After that, we have used the dict.values () method and it will extract only values from a given dictionary. Here is the Screenshot of the following given code.
Make the value a list, e.g.
a["abc"] = [1, 2, "bob"]
UPDATE:
There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.
key = "somekey" a.setdefault(key, []) a[key].append(1)
Results:
>>> a {'somekey': [1]}
Next, try:
key = "somekey" a.setdefault(key, []) a[key].append(2)
Results:
>>> a {'somekey': [1, 2]}
The magic of setdefault
is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault
returns the key you can combine these into a single line:
a.setdefault("somekey",[]).append("bob")
Results:
>>> a {'somekey': [1, 2, 'bob']}
You should look at the dict
methods, in particular the get()
method, and do some experiments to get comfortable with this.
How about
a["abc"] = [1, 2]
This will result in:
>>> a {'abc': [1, 2]}
Is that what you were looking for?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With