问题
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.
回答1:
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.
回答2:
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']
来源:https://stackoverflow.com/questions/51304016/break-very-long-lines-with-access-to-deeply-nested-dictionaries