Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update values for multiple keys in python

What is the cleanest way to update the values of multiple keys in a dictionary to the values stored in a tuple?

Example:

I want to go from

>>>mydict = {'a':None, 'b':None, 'c':None, 'd':None}
>>>mytuple = ('alpha', 'beta', 'delta')

to

>>>print mydict
{'a':'alpha', 'b':'beta', 'c':None, 'd':'delta'}

Is there an easy one-liner for this? Something like this seems to be getting close to what I want.

EDIT: I don't wish to assign values to keys based on their first letter. I'm just hoping for something like

mydict('a','b','d') = mytuple

Obviously that doesn't work, but I'm hoping for something similar to that.

like image 277
nfazzio Avatar asked Oct 11 '13 23:10

nfazzio


People also ask

How do you update multiple values in a dictionary?

If we want to update the values of multiple keys in the dictionary, then we can pass them as key-value pairs in the update() function. To bind keep multiple key-value pairs together, either we can use a list of tuples or we can create a temporary dictionary.

Can you have multiple values for a key in Python?

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 update a key in Python?

In order to update the value of an associated key, Python Dict has in-built method — dict. update() method to update a Python Dictionary. The dict. update() method is used to update a value associated with a key in the input dictionary.


1 Answers

If you're trying to create a new dictionary:

d = dict(zip(keys, valuetuple))

If you're trying to add to an existing one, just change the = to .update(…).

So, your example can be written as:

mydict.update(dict(zip('abd', mytuple))))

If you're doing this more than once, I'd wrap it up in a function, so you can write:

setitems(d, ('a', 'b', 'd'), mytuple)

Or maybe a "curried" function that parallels operator.itemgetter?

like image 141
abarnert Avatar answered Oct 03 '22 14:10

abarnert