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

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

问题描述

假设我有

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

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

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