Python 由元组索引的`dict`:分一杯羹
Python `dict` indexed by tuple: Getting a slice of the pie
假设我有
my_dict = {
("airport", "London"): "Heathrow",
("airport", "Tokyo"): "Narita",
("hipsters", "London"): "Soho"
}
什么是高效(不扫描所有键),但优雅的方式将所有机场从字典中取出,即预期输出 ["Heathrow", "Narita"]
。在可以按元组索引的数据库中,通常可以执行
airports = my_dict.get(("airport",*))
(但通常只有 'stars' 位于元组中最右边的位置,因为索引通常只按一个顺序存储)。
因为我想象 Python 以类似的方式(使用键的固有顺序)用元组键索引字典,我想可能有一种方法可以用这种方式对索引进行切片?
Edit1:添加了预期输出
Edit2:删除了最后一个短语。在条件中添加了“(不扫描所有键)”以使其更清楚。
What I'd like to avoid, if possible, is to go through all dictionary keys and filter them down.
为什么?为什么您认为 Python 正在执行相当于数据库完整 table 扫描的操作?过滤字典并不意味着顺序扫描它。
Python:
[value for key, value in my_dict.items() if key[0] == "airport"]
输出:
['Narita', 'Heathrow']
检查 "airport"
是否存在于字典的每个键中。
演示:
>>> [value for key, value in my_dict.items() if "airport" in key]
['Narita', 'Heathrow']
>>>
是的,嵌套字典将是更好的选择。
>>> my_dict = {
... "airport": {
... "London": "Heathrow",
... "Tokyo": "Narita",
... },
... "hipsters": {
... "London": "Soho"
... }
... }
>>>
>>> if "airport" in my_dict:
... result = my_dict["airport"].values()
... else:
... result = []
...
>>> print result
['Heathrow', 'Narita']
>>>
您的数据当前的组织方式不允许高效查找 - 基本上您必须扫描所有键。
字典是幕后的哈希表,访问值的唯一方法是获取键的哈希值 - 为此,您需要 整个键 。
使用这样的嵌套层次结构,这样您就可以进行直接的 O(1) 查找:
my_dict = {
"airport": {
"London": "Heathrow",
"Tokyo": "Narita",
},
"hipsters": {
"London": "Soho"
}
}
假设我有
my_dict = {
("airport", "London"): "Heathrow",
("airport", "Tokyo"): "Narita",
("hipsters", "London"): "Soho"
}
什么是高效(不扫描所有键),但优雅的方式将所有机场从字典中取出,即预期输出 ["Heathrow", "Narita"]
。在可以按元组索引的数据库中,通常可以执行
airports = my_dict.get(("airport",*))
(但通常只有 'stars' 位于元组中最右边的位置,因为索引通常只按一个顺序存储)。
因为我想象 Python 以类似的方式(使用键的固有顺序)用元组键索引字典,我想可能有一种方法可以用这种方式对索引进行切片?
Edit1:添加了预期输出
Edit2:删除了最后一个短语。在条件中添加了“(不扫描所有键)”以使其更清楚。
What I'd like to avoid, if possible, is to go through all dictionary keys and filter them down.
为什么?为什么您认为 Python 正在执行相当于数据库完整 table 扫描的操作?过滤字典并不意味着顺序扫描它。
Python:
[value for key, value in my_dict.items() if key[0] == "airport"]
输出:
['Narita', 'Heathrow']
检查 "airport"
是否存在于字典的每个键中。
演示:
>>> [value for key, value in my_dict.items() if "airport" in key]
['Narita', 'Heathrow']
>>>
是的,嵌套字典将是更好的选择。
>>> my_dict = {
... "airport": {
... "London": "Heathrow",
... "Tokyo": "Narita",
... },
... "hipsters": {
... "London": "Soho"
... }
... }
>>>
>>> if "airport" in my_dict:
... result = my_dict["airport"].values()
... else:
... result = []
...
>>> print result
['Heathrow', 'Narita']
>>>
您的数据当前的组织方式不允许高效查找 - 基本上您必须扫描所有键。
字典是幕后的哈希表,访问值的唯一方法是获取键的哈希值 - 为此,您需要 整个键 。
使用这样的嵌套层次结构,这样您就可以进行直接的 O(1) 查找:
my_dict = {
"airport": {
"London": "Heathrow",
"Tokyo": "Narita",
},
"hipsters": {
"London": "Soho"
}
}