如何快速访问与特定第二级键相对应的所有值,而不管Python字典中的第一级键如何? [英] How to quickly access all values corresponding to a specific second level key regardless of first level key in a Python dictionary?

查看:89
本文介绍了如何快速访问与特定第二级键相对应的所有值,而不管Python字典中的第一级键如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python字典,例如:

I have a Python Dictionary like:

Mydict = {'a':{'y':1,'x':5},'b':{'y':10,'x':8}}

Mydict = {'a': {'y': 1, 'x': 5}, 'b': {'y': 10, 'x': 8}}

是否有任何快速方法可以访问与键"x"相对应的值,在这种情况下,无论第一级键是什么,它都是第二级键?

Is there any quick way to access the values corresponding to the key: 'x', which in this case is a second level key, regardless of the first level key?

我知道可以使用for循环来完成此操作,

I know it can be done using a for loop like:

mylist=[]
for k in Mydict.keys():
    mylist.append(Mydict[k]['x'])

但是有什么快速的单行方法吗?

But is there any quick one line method for it?

推荐答案

使用由于不需要外部键,因此只需遍历内部字典,即可获得所需的'x'值.

Since you do not need the outer keys, you just iterate over the inner dicts, and get the desired 'x' value.

注意:只有在每个内部字典都具有'x'键的情况下,这才能起作用,为确保最大程度地减少错误,您可以执行以下操作:

Note: This will only work if each inner dict has an 'x' key, to be sure, and to minimize errors, you can do this:

mylist = [v.get('x', None) for v in Mydict.values()]

这将起到相同的作用,仅当字典中没有'x'键时,它才会返回None而不是KeyError异常.

This will function the same, only if there is no 'x' key in the dictionary, it will return None instead of a KeyError exception.

关于时间安排,以及哪种方法最好,请查看 Thorsten Kranz

For timing, and to see which method is best, look at the answer by Thorsten Kranz

这篇关于如何快速访问与特定第二级键相对应的所有值,而不管Python字典中的第一级键如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆