由元组索引的Python`dict`:得到一块馅饼 [英] Python `dict` indexed by tuple: Getting a slice of the pie

查看:177
本文介绍了由元组索引的Python`dict`:得到一块馅饼的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经

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

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

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?

编辑1:增加预期输出

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

这篇关于由元组索引的Python`dict`:得到一块馅饼的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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