'How to add multiple key-value pair to Dictionary at once?
I have a dictionary my_dict
having some elements like:
my_dict = {
'India':'Delhi',
'Canada':'Ottawa',
}
Now I want to add multiple dictionary key-value pair to a dict
like:
my_dict = {
'India': 'Delhi',
'Canada': 'Ottawa',
'USA': 'Washington',
'Brazil': 'Brasilia',
'Australia': 'Canberra',
}
Is there any possible way to do this? Because I don't want to add elements one after the another.
Solution 1:[1]
Use update()
method.
d= {'India':'Delhi','Canada':'Ottawa'}
d.update({'USA':'Washington','Brazil':'Brasilia','Australia':'Canberra'})
PS: Naming your dictionary as dict
is a horrible idea. It replaces the built in dict
.
Solution 2:[2]
To make things more interesting in this answer section, you can
add multiple dictionary key-value pair to a dict
by doing so (In Python 3.5 or greater):
d = {'India': 'Delhi', 'Canada': 'Ottawa'}
d = {**d, 'USA': 'Washington', 'Brazil': 'Brasilia', 'Australia': 'Canberra', 'India': 'Blaa'}
Which produces an output:
{'India': 'Blaa', 'Canada': 'Ottawa', 'USA': 'Washington', 'Brazil': 'Brasilia', 'Australia': 'Canberra'}
This alternative doesn't even seem memory inefficient. Which kind-a comes as a contradiction to one of "The Zen of Python" postulates,
There should be one-- and preferably only one --obvious way to do it
What I didn't like about the d.update() alternative are the round brackets, when I skim read and see round brackets, I usually think tuples. Either way, added this answer just to have some fun.
Solution 3:[3]
you have a few options:
- use
update()
:
d= {'India':'Delhi','Canada':'Ottawa'}
d.update({'USA':'Washington','Brazil':'Brasilia','Australia':'Canberra'})
- use
merge
:
d= {'India':'Delhi','Canada':'Ottawa'}
d2 = {'USA':'Washington','Brazil':'Brasilia','Australia':'Canberra'}
new_dict = d| d2
Solution 4:[4]
The update() method works well
As someone who primarily works in pandas data frames, I wanted to share how you can take values from a data frame and add them to a dictionary using update() and pd.to_dict().
import pandas as pd
Existing dictionary
my_dict = {
'India':'Delhi',
'Canada':'Ottawa',
}
Data frame with additional values you want to add to dictionary
country_index = ['USA','Brazil','Australia']
city_column = ['Washingon','Brasilia','Canberra']
new_values_df = pd.DataFrame(data=city_column, index=country_index, columns=['cities'])
Adding data frame values to dictionary
my_dict.update(new_values_df.to_dict(orient='dict')['cities'])
Dictionary now looks like
my_dict = {
'India': 'Delhi',
'Canada': 'Ottawa',
'USA': 'Washington',
'Brazil': 'Brasilia',
'Australia': 'Canberra',
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | masnun |
Solution 2 | Konstantin Grigorov |
Solution 3 | Tal Folkman |
Solution 4 | GameChanger |