Search code examples
python-3.xdictionarycomparison

Comparing values from nested dictionaries in Python 3


I have some code that uses a nested dictionary to hold results from a linear regression. The program runs a regression on multiple sets of data ('targets'), and stores the regression variables for each target as a dictionary, and these dictionaries are contained within another dictionary using the target name as the key with the value being the dictionary holding the variables. It's initialized like this (note that self.targets is just a list of the different targets):

self.results = {}
for keys in self.targets:
    self.results[keys] = {
        'lod': '', 'p': '', 'm': '', 'b': '', 'xr': ''}

In another method that gets called within a for-loop, the values in the dictionary for that target are filled:

for tar in targets:
    ...some calculations to produce the values...
    self.results[tar].update(
        'lod': lod, 'p': p, 'm': m, 'b': b, 'xr': xr)

Later on, I want to plot the different regressions on one plot. To do that, I want to find the maximum value of xr from the sub-dictionaries (xr is the right-bound needed to plot each regression).

I tried accessing all the xr values like self.results[:]['xr']. That didn't work, so I pulled the xr values in a for-loop:

xrs = []
for tar in self.targets:
    xrs.append(self.results[tar]['xr'])

and this gets the job done, as I can just do max(xrs) to find the largest value. I was wondering, though, if there was a more direct way to pull the maximum value of the 'xr' keys, without having to create a separate list as a middleman.


Solution

  • a generator comprehension might help:

    data = {
        "a" : {'lod': '', 'p': '', 'm': '', 'b': '', 'xr': 0},
        "b" : {'lod': '', 'p': '', 'm': '', 'b': '', 'xr': 1}
    }
    
    max_xr = max(value["xr"] for value in data.values())
    
    print(max_xr)
    

    That should give you 1 I think.