我在 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
作为元组键的第一个元素。一种方法是使用 for
和 if
:
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
我是一名优秀的程序员,十分优秀!