Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to respect PEP8 when accessing multiple nested dictionaries?

I have a line of code like this:

mydict['description_long'] = another_dict['key1'][0]['a_really_long_key']['another_long_key']['another_long_key3']['another_long_key4']['another_long_key5']

How do I format it so it adheres to the PEP8 guidelines?

like image 263
Strobe_ Avatar asked Jan 16 '17 23:01

Strobe_


People also ask

How do I iterate through a nested dictionary?

Nested dictionary means dictionary inside a dictionary and we are going to see every possible way of iterating over such a data structure. For this we will use for loop to iterate through a dictionary to get the all the key , values of nested dictionaries.

How do you access a multi level dictionary in Python?

Access Nested Dictionary Items You can access individual items in a nested dictionary by specifying key in multiple square brackets. If you refer to a key that is not in the nested dictionary, an exception is raised. To avoid such exception, you can use the special dictionary get() method.

How does Python store nested dictionaries?

One way to add a dictionary in the Nested dictionary is to add values one be one, Nested_dict[dict][key] = 'value'. Another way is to add the whole dictionary in one go, Nested_dict[dict] = { 'key': 'value'}.

Can I implement nested dictionary with list?

Given a list and dictionary, map each element of list with each item of dictionary, forming nested dictionary as value. Explanation : Index-wise key-value pairing from list [8] to dict {'Gfg' : 4} and so on.


2 Answers

The only relevant part of PEP8's style guidelines here is line length. Just break up the dict keys into their own separate lines. This makes the code way easier to read as well.

mydict['description_long'] = (another_dict['key1']
                                          [0]
                                          ['a_really_long_key']
                                          [etc.])
like image 171
PrestonH Avatar answered Nov 08 '22 17:11

PrestonH


I think I'd do something like this, add parens to go over multiple lines:

mydict['description_long'] = (
    another_dict['key1'][0]['a_really_long_key']['another_long_key']
    ['another_long_key3']['another_long_key4']['another_long_key5'])

Though it'd be better not to have such a deep structure in the first place, or to split up the lookup into several, if you can give those good names:

item = another_dict['key1'][0]['a_really_long_key']
part_name = item['another_long_key']['another_long_key3']
detail = part_name['another_long_key4']['another_long_key5']

At least that way the deep structure is documented a little.

like image 31
RemcoGerlich Avatar answered Nov 08 '22 18:11

RemcoGerlich