当值深3级时,如何按值对字典排序?

时间:2019-03-04 21:08:25

标签: python python-2.7 sorting dictionary

让我们说下面的字典是前面代码的输出:

{  
   '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'
      }
   }
}

我目前拥有的代码正在将生成器分配给变量,然后在for循环中使用该生成器:

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

for i in runs:...

我需要能够从dict[x]]['json']['region']中按区域对for循环进行排序,但要在字典上运行整整一秒的for循环,将它们设置为它们自己的嵌套列表,然后进行两次for循环,我想不出任何订购方法。我正在阅读一些有关如何按值排序的文档,但是当值嵌套3层时我无法弄清楚该怎么做。

我希望运行命令先运行dict[x]]['json']['region'] = APAC,再运行EMEA,再运行AMER 3。

我们正在使用Python 2.7,所以我将无法使用Python 3中存在的任何东西。

1 个答案:

答案 0 :(得分:2)

类似的事情应该起作用:

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

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

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