Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple assignments into a python dictionary

Is it possible to assign values to more than one keys of a dictionary in a more concise way than the one below?

I mean, let d be a dictionary initialized as below:

d={'a':1,'b':2,'c':3}

To assign values to multiple keys I need to do this:

d['a']=10
d['b']=200
d['c']=30

Can I achieve same with something like this:

d['a','b','c']=10,200,30

Thanks.

like image 851
ozi Avatar asked Jan 19 '14 20:01

ozi


People also ask

How do you add multiple items to a dictionary in Python?

By using the dictionary. update() function, we can easily append the multiple values in the existing dictionary. In Python, the dictionary. update() method will help the user to update the dictionary elements or if it is not present in the dictionary then it will insert the key-value pair.

Does Python support multiple assignment?

Multiple assignment in Python: Assign multiple values or the same value to multiple variables. In Python, use the = operator to assign values to variables. You can assign values to multiple variables on one line.

What is multiple assignment in Python?

Multiple assignment (also known as tuple unpacking or iterable unpacking) allows you to assign multiple variables at the same time in one line of code. This feature often seems simple after you've learned about it, but it can be tricky to recall multiple assignment when you need it most.

How do you update a dictionary with multiple values?

In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.


3 Answers

You can use dict.update:

d.update({'a': 10, 'c': 200, 'c': 30})

This will overwrite the values for existing keys and add new key-value-pairs for keys that do not already exist.

like image 83
Aamir Rind Avatar answered Sep 30 '22 08:09

Aamir Rind


You can also simply use the multiple assigment semantics:

d['a'], d['b'], d['c'] = 10, 200, 30
like image 34
Delgan Avatar answered Sep 30 '22 06:09

Delgan


You can always wrap it in a function:

def multiassign(d, keys, values):
    d.update(zip(keys, values))

Even if you didn't know about update, you could write it like this:

def multiassign(d, keys, values):
    for k, v in zip(keys, values):
        d[k] = v

Or you can even write a dict subclass that gives you exactly the syntax you wanted:

class EasyDict(dict):
    def __getitem__(self, key):
        if isinstance(key, tuple):
            return [super().__getitem__(k) for k in key]
        else:
            return super().__getitem__(key)
    def __setitem__(self, key, value):
        if isinstance(key, tuple):
            self.update(zip(key, value))
        else:
            super().__setitem__(key, value)
    def __delitem__(self, key, value):
        if isinstance(key, tuple):
            for k in key: super().__delitem__(k)
        else:
            super().__setitem__(key, value)

Now:

>>> d = {'a': 1, 'd': 4}
>>> multiassign(d, ['a', 'b', 'c'], [10, 200, 300])
>>> d
{'a': 10, 'b': 200, 'c': 300, 'd': 4}
>>> d2 = EasyDict({'a': 1, 'd': 4})
>>> d2['a', 'b', 'c'] = 100, 200, 300
>>> d2
{'a': 10, 'b': 200, 'c': 300, 'd': 4}

Just be aware that it will obviously no longer be possible to use tuples as keys in an EasyDict.

Also, if you were going to use this for something serious, you'd probably want to improve the error handling. (d['a', 'b'] = 1 will give a cryptic message about zip argument #2 must support iteration, d['a', 'b', 'c'] = 1, 2 will silently work and do nothing to c, etc.)

like image 22
abarnert Avatar answered Sep 30 '22 08:09

abarnert