Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple key-value pair to Dictionary at once?

Tags:

python

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.

like image 815
arun chauhan Avatar asked Aug 20 '16 16:08

arun chauhan


People also ask

Can we add multiple values to key in on dictionary?

General Idea: In Python, if we want a dictionary to have multiple values for a single key, we need to store these values in their own container within the dictionary. To do so, we need to use a container as a value and add our multiple values to that container. Common containers are lists, tuples, and sets.

How do you add multiple values to a dictionary in python?

Append multiple values to a key in a dictionary We need to make sure that if the key already exists in the dictionary or not. If yes, then append these new values to the existing values of the key. If no, then and add an empty list as a value for that key and then add these values in that list.


2 Answers

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.

like image 156
Konstantin Grigorov Avatar answered Oct 24 '22 15:10

Konstantin Grigorov


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.

like image 20
masnun Avatar answered Oct 24 '22 14:10

masnun