简体   繁体   中英

Break very long lines with access to deeply nested dictionaries

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.

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM