I access a deeply nested dictionary and want to break very long lines properly. Let's assume I have this and want to break the line to conform with PEP8. (The actual line is of course longer, this is just an example.)
some_dict['foo']['bar']['baz'] = 1
How would you break the line, assuming the whole
some_dict['foo']['bar']['baz']
does not fit on one line anymore? There are a lot of examples for breaking long lines, but I couldn't find one for this dictionary access based question.
Update: Please note that I want to assign something to that dictionary. The proposed duplicate only talks about getting a value from that kind of dictionary.
Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step. For Python >= 3.3, change the import to from collections.
There is nothing inherently wrong with nested dicts. Anything can be a dict value, and it can make sense for a dict to be one. A lot of the time when people make nested dicts, their problems could be solved slightly more easily by using a dict with tuples for keys.
A dictionary can contain any object type except another dictionary. Dictionaries are mutable. Dictionaries can be nested to any depth. Items are accessed by their position in a dictionary.
To remove an element from a nested dictionary, use the del() method. To remove a dictionary from a nested dictionary there are two methods available in python. The pop() method returns the removed dictionary.
Here's the solution I'm most happy with. It boils down to:
some_dict['foo']['bar']['baz'] = 1
is equal to
(some_dict['foo']['bar']['baz']) = 1
which you can break anywhere you want, like so:
(some_dict['foo']
['bar']['baz']) = 1
Which should be aligned with Pythons preferred way to break long lines, using Python's implied line continuation inside parentheses.
If you are dealing with deeply nested dictionaries, you should consider another data structure, refactoring with tuple keys, or defining your path via a list.
Here's an example of the last option which helps specifically with PEP8:
from operator import getitem
from functools import reduce
def get_val(dataDict, mapList):
return reduce(getitem, mapList, dataDict)
d = {'foo': {'bar': {}}}
*path, key = ['foo', 'bar', 'baz']
get_val(d, path)[key] = 1
Note that lists don't need line escapes between elements. This is perfectly fine:
*path, key = ['foo',
'bar',
'baz']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With