gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:06:32 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com