简体   繁体   English

在Python中使用元组作为字典键

[英]Using tuple as a dictionary key in Python

I am trying to work with a dictionary with tuples of n values as keys. 我正在尝试使用n值为元组的字典作为键。 I want to find tuples whose 2nd value is 10 (for example) 我想找到第二个值为10的元组(例如)

('HI', '10', '10', '10', '10', '10000', 'true', '0.5GiB', '8', '100000s', '100MiB')
('HI', '100', '10', '10', '10', '100', 'false', '0.5GiB', '8', '100000s', '100MiB')
('HI', '100', '10', '10', '10', '1000', 'true', '0.7GiB', '8', '1000s', '100MiB')

Any ideads how I can do it? 任何想法我怎么能这样做? THanks! 谢谢!

For that particular scenario, you'd have to iterate over all of the keys and test them against your predicate: 对于该特定场景,您必须迭代所有键并针对谓词测试它们:

results = set(k for k in your_dict if k[1] == '10')

If you wanted to do this more quickly for repeated lookups and you knew ahead of time what field(s) you'd be checking, you could build indices that map between values for a particular index in each tuple to the keys that have a given value: 如果您希望更快地执行此操作以进行重复查找,并且您事先知道要检查哪些字段,则可以构建索引,将每个元组中特定索引的值映射到具有给定字符的键之间值:

from collections import defaultdict

index_2nd = defaultdict(set)
for k in your_dict:
    index_2nd[k[1]].add(k)

And then you could just use that to look up a particular value: 然后你可以用它来查找一个特定的值:

results = index_2nd['10']

You can't, not easily. 你不能,不容易。 You'd have to loop through all keys to check for those that match: 您必须遍历所有密钥以检查匹配的密钥:

matching = [key for key in yourtupledict if key[1] == '10']

If you need to do this a lot in your application, you'd be better off creating indices; 如果你需要在你的应用程序中做很多事情,你最好创建索引; dictionaries or similar that map the second value in all your keys to specific keys. 将所有键中的第二个值映射到特定键的字典或类似字典。

Use iterkeys() to iterate over keys 使用iterkeys()迭代键

d = {(1,2,3):1,(1,2,4):2,(2,2,3):3}

for k in d.iterkeys():
    if k[0] == 1:
        print k
def find(key_element):
    return [value for key, value in a.iteritems() if len(key) > 1 and key[1] == key_element]

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

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