Python 复杂的字典键

标签 python dictionary key

我的问题与字典键有关。我想为任何单个对象设置一个包含 3 个键的字典。键必须按顺序排列,并且可以具有广泛的值。例如,

dictionary = {(key1,key2,key3) : object}

key1 可以是 1 到 10 之间的任何值 key2 可以是 11 到 20 之间的任何值 key3 可以是 21 到 30 之间的任何值

放置键的顺序很重要。

更具体地说,我的键对应于 x,y,z 笛卡尔坐标的范围,许多对象在其中 float 。我希望能够根据对象的 x,y,z 对对象的相对位置进行排序职位。

有什么方法可以设置,还是我必须采取不同的方法? 谢谢你的帮助!

最佳答案

当然可以,也可以为此创建单个字符串键 - 只需为您的键合并字符串结果,例如 ','.join([k1,k2,k3])

Read more about dictionaries.

dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

所以你尝试使用元组作为键,这没关系。

请注意,python 中的字典没有排序。您可以为此使用 collections.OrderedDict。还要建立正确的排序使用 sort/sorted functions指定参数键以按您想要的方式排序。

编辑样本:

from itertools import product
myDict = {}
for x,y,z in product(range(10), range(10,20), range(20,30)):
    myDict[(x,y,z)] = sum([x,y,z])

关于Python 复杂的字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13523070/

相关文章:

python - 在字典中找到一个值?

python - 如何将这个数据框改得更长?

python - 如何在Python中将文本绘制为位图?

python - 字典 Python 中 If-Condition 上的 KeyError

c# - C# HashSet 是否通过 Equals 然后通过 GetHashCode 检查重复项?

android - 当用户按下键盘上的返回键时隐藏键盘

Javascript 将 2 个新键动态添加到新字典对象中,或者如果存在则递增

python - Python strip 函数的奇怪行为

python - 用于 Python 2.7 的 Perforce API

key - 是否有任何开源工具可以在团队成员之间共享 .env 文件?