python - 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.
解决方案
像这样的东西应该工作:
sorted(dict.keys(), key=lambda k: dict[k]['json']['region'])
这将返回按地区排序的键列表:
['3', '1', '2']
推荐阅读
- c# - 通过将状态存储到作用域局部变量中来避免关闭快速路径
- database - 这种可变长度日期编码格式是什么?
- github - 如何在 GitHub 上设置文件以供下载?
- c++ - 如何在 constexpr 中进行编译时错误检查?
- python - 为什么当输入到下一个变换时 GroupIntoBatches 输出会被细分
- ios - 如果不是从 xcode 运行,iOS 应用程序缺少 DYLD
- matplotlib - 如何使用 Embed set_image 将图像从 MatPlotlib 嵌入到 Discord.py 而不存储图像?
- javascript - React-Native:仅在下一个动作/重新渲染时影响视图的状态变化?
- jquery - 从无线电输入全局保存变量
- python - Django:Channels 和 Web Socket,如何让群聊独占