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 a simple single line for this? Something like this seems to be getting closer to what I want.

EDIT: I don't want to assign values ​​to keys based on their first letter. I just hope for something like

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

Obviously this will not work, but I hope for something like that.

+4
source share
4 answers

If you are trying to create a new dictionary:

d = dict(zip(keys, valuetuple))

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

So, your example can be written as:

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

, , :

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

, , "curried", operator.itemgetter?

+4

, , .

keys = [ 'a', 'b', 'c', 'd']
values = ['alpha', 'beta', 'delta']
dictionary = dict([(k,v) for k in keys for v in values if v.startswith(k)])
print dictionary #prints {'a': 'alpha', 'b': 'beta', 'd': 'delta'}
0

Assuming the association key ↔ is the first letter of the value, it is the first letter of the key.

dict( (v[0],v) for v in mytuple if v[0] in mydict)
0
source

In this case, I would avoid single-line. This makes the code more readable.

for t in mytuple:
    if t[0] in mydict.keys():
        mydict[t[0]] = t

If you want to add mytuple elements, even if the key does not exist, simply delete the statement if.

0
source

All Articles