Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
找到一个键';从python字典列表中选择s值_Python_List_Dictionary_Find - Fatal编程技术网

找到一个键';从python字典列表中选择s值

找到一个键';从python字典列表中选择s值,python,list,dictionary,find,Python,List,Dictionary,Find,如何从字典列表中获取给定键的值 mylist= [ { 'powerpoint_color': 'blue', 'client_name': 'Sport Parents (Regrouped)' }, { 'sort_order': 'ascending', 'chart_layout': '1', 'chart_type': 'bar' } ] “mylist”中的词典编号未知,我想查找附加到键“s

如何从字典列表中获取给定键的值

mylist= [
    {
      'powerpoint_color': 'blue',
      'client_name': 'Sport Parents (Regrouped)'
    },
    {
      'sort_order': 'ascending',
      'chart_layout': '1',
      'chart_type': 'bar'
    }
]
“mylist”中的词典编号未知,我想查找附加到键“sort\u order”的值

我失败的尝试:

for key in mylist:
    for value in key:
        print key['sort_order']
谢谢

结果:

ascending

您还可以将所有词典合并成一个dict,并访问:

combined_d = {key: value for d in mylist for key,value in d.iteritems() }
print combined_d["sort_order"]

您可以使用以下代码获取它:

for d in mylist:
    if 'sort_order' in d:
        print(d['sort_order'])
首先,对列表进行迭代,对于每个字典,检查它是否需要键以及是否得到值。

类似的内容

for hash in mylist:
    if "sort_order" in hash: print hash ["sort_order"]

虽然不可读,但此版本:

  • 提供短路
  • 避免重复查找


请注意,如果您的某些键的计算结果为false,则此操作将失败,但开发一个不从这个起点出发的版本并不困难

感谢您的解释。我知道我现在错在哪里了。我将使用列表理解法,但给这个投票@克里斯·亚当斯-谢谢你清理我的名单。
for hash in mylist:
    if "sort_order" in hash: print hash ["sort_order"]
print reduce( lambda a,b: a or b, (l.get("sort_order") for l in mylist) )