Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to edit dictionary value python

Tags:

python

pep8

I have written the following code in two different ways. I am trying to find the "correct pythonic" way of doing it. I will explain the reasons for both.

First way, EAFP. This one uses pythons EAFP priciple, but causes some code duplication.

try:
    my_dict['foo']['bar'] = some_var
except KeyError:
    my_dict['foo'] = {}
    my_dict['foo']['bar'] = some_var

Second way, LBYL. LBYL is not exactly considered pythonic, but it removes the code duplication.

if 'foo' not in my_dict:
    my_dict['foo'] = {}

my_dict['foo']['bar'] = some_var

Which way would be considered best? Or is there a better way?

like image 804
Nick Humrich Avatar asked Jul 17 '14 18:07

Nick Humrich


People also ask

Can you change the values of a dictionary Python?

update() function. In case you need a declarative solution, you can use dict. update() to change values in a dict.

Can you modify the value in a dictionary?

Modifying a value in a dictionary is pretty similar to modifying an element in a list. You give the name of the dictionary and then the key in square brackets, and set that equal to the new value. dictionary: A collection of key-value pairs.

How do you change a dictionary value?

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.

Which method will modify the value of a key in a dictionary?

We use the pop method to change the key value name.


1 Answers

I would say a seasoned Python developer would either use

dict.setdefault or collections.defaultdict

my_dict.setdefault('foo', {})['bar'] = some_var

or

from collection import defaultdict
my_dict = defaultdict(dict)
my_dict['foo']['bar'] = some_var

Also for the sake of completeness, I will introduce you to a recursive defaultdict pattern, which allows for dictionaries with infinite depth without any key error

>>> from collections import defaultdict
>>> def tree(): return defaultdict(tree)

>>> my_dict = tree()
>>> my_dict['foo']['bar']['spam']['egg'] = 0
>>> my_dict
defaultdict(<function tree at 0x026FFDB0>, {'foo': defaultdict(<function tree at 0x026FFDB0>, {'bar': defaultdict(<function tree at 0x026FFDB0>, {'spam': defaultdict(<function tree at 0x026FFDB0>, {'egg': 0})})})})
like image 103
Abhijit Avatar answered Sep 24 '22 00:09

Abhijit