如何在Python的字典中要求子键的键? [英] How can I ask for a key of a subkey in a dictionary in Python?

查看:307
本文介绍了如何在Python的字典中要求子键的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的词典中有词典,该如何在恒定时间内索取密钥? 例如:

If I have a dictionary in a dictionary, how can I ask for a key in constant time? For example:

def get_hobby(hobby):
    d = {'An' : {'Hobby': "Paintball", 'Age' : 22}, 'Jef' : {'Hobby' : "Football", 'Age': 24}, 'Jos' : {'Hobby': "Paintball", 'Age' : 46}}
assert get_hobby("Paintball") == ['An', 'Jos']

这不起作用:

return d.keys[hobby]

推荐答案

使用列表理解:

return [name for name, props in d.items() if props['Hobby'] == hobby]

d.items()给您一系列的(key, value)对,其中值是嵌套字典.列表理解通过将hobby变量与嵌套的'Hobby'键进行匹配来过滤这些内容,从而生成过滤器测试为其返回True的名称的列表.

d.items() gives you a sequence of (key, value) pairs, where the value is the nested dictionary. The list comprehension filters these by matching the hobby variable to the nested 'Hobby' key, producing a list of the names for which the filter test returns True.

您不能在恒定时间内要求输入密钥,因为该数字是可变的.

You cannot ask for the keys in constant time, because that number is variable.

演示:

>>> def get_hobby(hobby):
...     d = {'An' : {'Hobby': "Paintball", 'Age' : 22}, 'Jef' : {'Hobby' : "Football", 'Age': 24}, 'Jos' : {'Hobby': "Paintball", 'Age' : 46}}
...     return [name for name, props in d.items() if props['Hobby'] == hobby]
... 
>>> get_hobby("Paintball")
['Jos', 'An']

请注意,返回的键列表是任意顺序,因为字典没有设置的顺序.您不能简单地对照另一个列表测试该列表并期望它每次都相等,因为列表确实具有顺序.确切的顺序取决于 Python哈希种子以及插入和字典的删除历史记录.

Note that the returned list of keys is in arbitrary order, because dictionaries have no set ordering. You cannot simply test that list against another list and expect it to be equal every single time, because lists do have order. The exact order depends on the Python hash seed and the insertion and deletion history of the dictionary.

您可能想返回一个 set ;集合也没有排序,并且可以更好地反映返回的匹配键的性质:

You may want to return a set instead; sets do not have ordering either and better reflect the nature of the matching keys returned:

return {name for name, props in d.items() if props['Hobby'] == hobby}

之后您的主张将变为:

assert get_hobby("Paintball") == {'An', 'Jos'}

这篇关于如何在Python的字典中要求子键的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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