每个值有多个键 [英] Multiple keys per value
问题描述
是否可以在 Python 字典中为每个值分配多个键.一种可能的解决方案是为每个键分配值:
Is it possible to assign multiple keys per value in a Python dictionary. One possible solution is to assign value to each key:
dict = {'k1':'v1', 'k2':'v1', 'k3':'v1', 'k4':'v2'}
但这不是内存效率,因为我的数据文件 > 2 GB.否则,您可以制作字典键的字典:
but this is not memory efficient since my data file is > 2 GB. Otherwise you could make a dictionary of dictionary keys:
key_dic = {'k1':'k1', 'k2':'k1', 'k3':'k1', 'k4':'k4'}
dict = {'k1':'v1', 'k4':'v2'}
main_key = key_dict['k2']
value = dict[main_key]
这也很费时间和精力,因为我必须两次浏览整个字典/文件.有没有其他简单的内置 Python 解决方案?
This is also very time and effort consuming because I have to go through whole dictionary/file twice. Is there any other easy and inbuilt Python solution?
注意:我的字典值不是简单的字符串(如问题v1"、v2"),而是复杂的对象(包含不同的其他字典/列表等,无法对它们进行腌制)
注意:问题似乎类似于 如何对同一个字典值同时使用键和索引?但我不是在寻找有序/索引字典,而是在寻找除此问题中提到的两个之外的其他有效解决方案(如果有).
Note: my dictionary values are not simple string (as in the question 'v1', 'v2') rather complex objects (contains different other dictionary/list etc. and not possible to pickle them)
Note: the question seems similar as How can I use both a key and an index for the same dictionary value?
But I am not looking for ordered/indexed dictionary and I am looking for other efficient solutions (if any) other then the two mentioned in this question.
推荐答案
值是什么类型?
dict = {'k1':MyClass(1), 'k2':MyClass(1)}
会给出重复的值对象,但是
will give duplicate value objects, but
v1 = MyClass(1)
dict = {'k1':v1, 'k2':v1}
导致两个键都指向同一个实际对象.
results in both keys referring to the same actual object.
在最初的问题中,您的值是字符串:即使您两次声明相同的字符串,我认为在这种情况下它们会被实习到同一个对象
In the original question, your values are strings: even though you're declaring the same string twice, I think they'll be interned to the same object in that case
注意.如果您不确定是否最终得到了重复项,您可以像这样找到:
NB. if you're not sure whether you've ended up with duplicates, you can find out like so:
if dict['k1'] is dict['k2']:
print("good: k1 and k2 refer to the same instance")
else:
print("bad: k1 and k2 refer to different instances")
(is
检查感谢 J.F.Sebastian,替换 id()
)
(is
check thanks to J.F.Sebastian, replacing id()
)
这篇关于每个值有多个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!