Reputation: 684
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.
Upvotes: 17
Views: 24538
Reputation: 106
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',
}
Upvotes: 0
Reputation: 2581
you have a few options:
update()
:d= {'India':'Delhi','Canada':'Ottawa'}
d.update({'USA':'Washington','Brazil':'Brasilia','Australia':'Canberra'})
merge
:d= {'India':'Delhi','Canada':'Ottawa'}
d2 = {'USA':'Washington','Brazil':'Brasilia','Australia':'Canberra'}
new_dict = d| d2
Upvotes: 1
Reputation: 1642
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.
Upvotes: 5
Reputation: 11916
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
.
Upvotes: 24