首页 > 解决方案 > How do I sort a dictionary by a value when the value is 3 levels deep?

问题描述

Let's say that the following dictionary is the output of the previous code:

{  
   '1':{  
      'json':{  
         'stuff2':[  
            '123',
            '234',
            '345'
         ],
         'region':'APAC'
      },
      'stuff':{  
         'search1':'1231245132512',
         'search2':'235346262346'
      }
   },
   '2':{  
      'json':{  
         'stuff2':[  
            '123',
            '234',
            '345'
         ],
         'region':'EMEA'
      },
      'stuff':{  
         'search1':'1231245132512',
         'search2':'235346262346'
      }
   },
   '3':{  
      'json':{  
         'stuff2':[  
            '123',
            '234',
            '345'
         ],
         'region':'AMER'
      },
      'stuff':{  
         'search1':'1231245132512',
         'search2':'235346262346'
      }
   }
}

The code I have is currently assigning a generator to a variable and then using that generator in a for loop:

runs = (unimportantFunc(x,y,z) for x,y in dict.items())

for i in runs:...

I need to be able to order the for loop by region from the dict[x]]['json']['region'] but short of running an entire second for loop over the dictionary, setting them into their own nested lists, and then doing a double for loop, I can't think of any way to order them. I was reading some documentation on how to sort by values, but I can't figure out how to do that when the value is nested 3 deep.

I want the run to be ordered to run dict[x]]['json']['region'] = APAC first, EMEA second and AMER 3rd.

We're using Python 2.7, so I won't be able to use anything that exists in Python 3.

标签: pythonpython-2.7sortingdictionary

解决方案


像这样的东西应该工作:

sorted(dict.keys(), key=lambda k: dict[k]['json']['region'])

这将返回按地区排序的键列表:

['3', '1', '2']

推荐阅读