patternpythonMinor
Add 100 to all values in nested dictionary
Viewed 0 times
allnested100valuesdictionaryadd
Problem
I want to change all values in a multidimensional dictionary. I have written this line of code, which does what I want it to do and I am trying to find out if this is the optimal way or just some convoluted solution I came up with:
dict_data = dict([x,dict([y, dict_data[x][y]+100] for y in dict_data[x])] for x in dict_data)Solution
If you're using both keys and values from a dictionary, then using the
is neater than iterating over the keys and including
Note that using
items method:... for key, val in dct.items() ...is neater than iterating over the keys and including
dct[key] everywhere. In Python 2.7+, you can use a dictionary comprehension (see e.g. the tutorial) rather than pass a list comprehension to dict:dict_data = {key: {key_: val_+100 for key_, val_ in val.items()}
for key, val in dict_data.items()}Note that using
key, val and the _ versions also makes it clearer what's happening than x and y.Code Snippets
... for key, val in dct.items() ...dict_data = {key: {key_: val_+100 for key_, val_ in val.items()}
for key, val in dict_data.items()}Context
StackExchange Code Review Q#90413, answer score: 4
Revisions (0)
No revisions yet.