简体   繁体   English

具有元组键的字典:所有具有相同第一个元素的元组

[英]Dictionary with tuples key: All tuples with the same first element

I have dictionary in python whose keys are tuples, like: 我在python中有字典,其键是元组,例如:

my-dict={(1,'a'):value1, (1,'b'):value2, (1,'c'):value3, (2,'a'):value4, 
(2,'b'):value5,(3,'a'):value6}

I need to access all values whose keys have the same first argument. 我需要访问其键具有相同第一个参数的所有值。 For example, I need to access 例如,我需要访问

{(1,'a'):value1, (1,'b'):value2, (1,'c'):value3}  

because all of them have 1 as the first element of the tuple key. 因为它们所有人都以1作为元组键的第一个元素。 One way is to use a for and if : 一种方法是使用forif

for key in my-dict:
    if key[0]==1:
       do something

However, my actual dictionary and data are very huge and this method takes a lot of time. 但是,我的实际字典和数据非常庞大,此方法需要大量时间。 Is there any other way to efficiently do this? 还有其他有效方法吗?

You lose out on the benefits of creating a dictionary if you have to search through all its keys again. 如果您必须再次搜索所有字典键,则会失去创建字典的好处。 A good solution would be to create another dictionary That holds all keys which start with the correct first element. 一个好的解决方案是创建另一个字典,该字典包含以正确的第一个元素开头的所有键。

my_dict={(1,'a'):'value1', (1,'b'):'value2', (1,'c'):'value3', (2,'a'):'value4', 
(2,'b'):'value5',(3,'a'):'value6'}

from collections import defaultdict

mapping = defaultdict(list) #You do not need a defaultdict per se, i just find them more graceful when you do not have a certain key.

for k in my_dict:
    mapping[k[0]].append(k)

Mapping now looks like this: 现在的映射如下所示:

defaultdict(list,
            {1: [(1, 'a'), (1, 'b'), (1, 'c')],
             2: [(2, 'a'), (2, 'b')],
             3: [(3, 'a')]})

Now Just use the dictionary to lookup the keys needed in your original dictionary. 现在,只需使用字典来查找原始字典中所需的键。

first_element = 1
#Now just use the lookup to do some actions
for key in mapping[first_element]:
    value = my_dict[key]
    print(value)
    #Do something

Output: 输出:

value1
value2
value3

The dict built-in type maps hashable values to arbitrary objects. dict内置类型将可哈希值映射到任意对象。 In your dictionary, the tuples (1, 'a') , (1, 'b') , etc. all have different hashes. 在您的字典中,元组(1, 'a')(1, 'b')等都有不同的哈希值。

You could try using Pandas multi-indexes to accomplish this. 您可以尝试使用Pandas多索引来完成此操作。 Here is a good example. 是一个很好的例子。

Alternatively, as one of the comments suggested, a nested dictionary may be more appropriate here. 替代地,如所建议的评论之一,在此嵌套字典可能更合适。 You can convert it from my_dict via 您可以通过以下方式从my_dict进行转换

from collections import defaultdict

nested_dict = defaultdict(dict)  # not necessary, but saves a line
for tup_key, value in my_dict.items():
    key1, key2 = tup_key
    nested_dict[key1][key2] = value

Then something like nested_dict[1] would give you 然后像nested_dict[1]这样的东西会给你

{'a':value1, 'b':value2, 'c':value3}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM