元组索引的 Python `dict`:获取一块饼

2022-01-20 00:00:00 python indexing dictionary tuples

问题描述

假设我有

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

什么是从字典中取出所有机场的有效(不扫描所有键)但优雅的方法,即预期输出 ["Heathrow", "Narita"].在可以按元组索引的数据库中,通常可以执行类似

What is an efficient (no scanning of all keys), yet elegant way to get all airports out of this dictionary, i.e. expected output ["Heathrow", "Narita"]. In databases that can index by tuples, it's usually possible to do something like

airports = my_dict.get(("airport",*))

(但通常只有星"位于元组中最右边的位置,因为索引通常只以一种顺序存储).

(but usually only with the 'stars' sitting at the rightmost places in the tuple since the index usually is only stored in one order).

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

Since I imagine Python to index dictionary with tuple keys in a similar way (using the keys's inherent order), I imagine there might be a method I could use to slice the index this way?

Edit1:添加预期输出

Added expected output

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

Removed last phrase. Added '(no scanning of all keys)' to the conditions to make it clearer.


解决方案

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

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.

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

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"
  }
}

相关文章