python - 带元组键的字典 : All tuples with the same first element

标签 python search tuples key

我在 python 中有一个字典,它的键是元组,比如:

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

我需要访问其键具有相同第一个参数的所有值。例如,我需要访问

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

因为它们都以 1 作为元组键的第一个元素。一种方法是使用 forif:

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

但是,我的实际字典和数据非常庞大,这种方法需要花费很多时间。有没有其他方法可以有效地做到这一点?

最佳答案

如果您必须再次搜索字典的所有键,您就失去了创建字典的好处。一个好的解决方案是创建另一个字典,它包含所有以正确的第一个元素开头的键。

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)

映射现在看起来像这样:

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

现在只需使用字典来查找原始字典中所需的键。

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

输出:

value1
value2
value3

关于python - 带元组键的字典 : All tuples with the same first element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53906534/

相关文章:

python - invalid\x escape 模块没有定义 __module_name__

c++ - 在 n 个皇后主冲突搜索中表现不佳

database - 单字英语名词列表?

python - 字典中元组第一项的平均值

python - 确定特定文件中元组中每个元素的计数是否为 0 - 如果为 0,则标记该元素

python telnetlib 模块 : reading and waiting for responses

python - Django 1.6 : What should be the location of the sitemap. py 文件?

python - 如何使用 NLTK nltk.tokenize.texttiling 将文本拆分为段落?

javascript - 如何提高智能手机上表格过滤 JavaScript 的速度?

python - 对运算符表达式的结果调用函数? (掩码==instance_id).astype(np.uint8)