由元组索引的Python`dict`:得到一块馅饼

时间:2015-06-04 06:15:51

标签: python dictionary indexing tuples

假设我有

my_dict = {
  ("airport", "London"): "Heathrow",
  ("airport", "Tokyo"): "Narita",
  ("hipsters", "London"): "Soho"
}

什么是高效(不扫描所有键),但是优雅的方式让所有机场都离开这个词典,即预期输出["Heathrow", "Narita"]。在可以通过元组索引的数据库中,通常可以执行类似

的操作
airports = my_dict.get(("airport",*))

(但通常只有“星星”位于元组中最右边的位置,因为索引通常只存储在一个顺序中。)

由于我想用Python以类似的方式使用元组键对字典进行索引(使用键的固有顺序),我想可能有一种方法可以用来以这种方式对索引进行切片?

Edit1:添加了预期输出

Edit2:删除了最后一个短语。在条件中添加了“(不扫描所有键)”以使其更清晰。

3 个答案:

答案 0 :(得分:4)

您的数据当前的组织方式不允许有效查找 - 实质上您必须扫描所有键

字典是幕后的哈希表,访问值的唯一方法是获取密钥的哈希 - 为此,您需要整个密钥

使用这样的嵌套层次结构,因此您可以直接进行O(1)查找:

my_dict = {
  "airport": {
     "London": "Heathrow",
     "Tokyo": "Narita",
  },
  "hipsters": {
     "London": "Soho"
  }
}

答案 1 :(得分:3)

检查字典中的每个键都有"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']
>>> 

答案 2 :(得分:1)

  

如果可能,我希望避免使用所有字典键并将其过滤掉。

为什么呢?为什么你认为Python相当于数据库全表扫描?过滤字典并不意味着顺序扫描它。

的Python:

[value for  key, value in my_dict.items() if key[0] == "airport"]

输出:

['Narita', 'Heathrow']
相关问题