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?
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.
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.
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'}.
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.
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.])
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.
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