Python `dict` indexed by tuple: Getting a slice of the pie

让人想犯罪 __ 提交于 2019-12-01 21:23:52

The way your data is currently organized doesn't allow efficient lookup - essentially you have to scan all the keys.

Dictionaries are hash tables behind the scenes, and the only way to access a value is to get the hash of the key - and for that, you need the whole key.

Use a nested hierarchy like this, so you can do a direct O(1) lookup:

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

Check "airport" is present in the every key in the dictionary.

Demo:

>>> [value for  key, value in my_dict.items() if  "airport" in key]
['Narita', 'Heathrow']
>>> 

Yes, Nested dictionary will be better option.

>>> 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']
>>> 

What I'd like to avoid, if possible, is to go through all dictionary keys and filter them down.

Why? Why do you think Python is doing the equivalent of a DB full table scan? Filtering a dictionary does not mean sequential scanning it.

Python:

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

Output:

['Narita', 'Heathrow']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!