简体   繁体   English

使用元组作为字典键

[英]Work with tuples as dictionary keys

I use GraphViz library and in some case, it retuns me a dictionary having tuple as keys. 我使用GraphViz库,在某些情况下,它使我重新调整了以元组为键的字典。

{(4, 7): 0, (2, 6): 1, (10, 4): 1, (5, 11): 1, (4, 5): 1,
(2, 8): 0, (8, 11): 0, (10, 0): 1, (6, 11): 1, (9, 11): 1,
(1, 9): 0, (10, 1): 0, (7, 11): 1, (0, 9): 1, (3, 7): 1,
(10, 3): 1, (10, 2): 1}

For some reason, I would like to get the second number in the tuples where : the first number == 10 and the value == 1 出于某种原因,我想在元组获得第二个数字, 其中 :第一个数字== 10 值== 1

I've tried to access the dictionary with (10, ) but I think this syntax is not allowed in python. 我尝试使用(10, )访问字典(10, )但我认为python中不允许使用此语法。

the answer should be : [4 ,0 ,3 , 2] 答案应该是: [4 ,0 ,3 , 2]

You'll have to iterate over the dictionary, eg: 您必须遍历字典,例如:

In [1]: d = {(4, 7): 0, (2, 6): 1, (10, 4): 1, (5, 11): 1, (4, 5): 1,
   ...: (2, 8): 0, (8, 11): 0, (10, 0): 1, (6, 11): 1, (9, 11): 1,
   ...: (1, 9): 0, (10, 1): 0, (7, 11): 1, (0, 9): 1, (3, 7): 1,
   ...: (10, 3): 1, (10, 2): 1}

In [2]: [b for (a, b), v in d.items() if a == 10 and v == 1]
Out[2]: [4, 0, 3, 2]
result=[]
for key in your_dict.keys():
  if key[0]==10 and your_dict[key]==1:
    result.append(key[1])

(10, ) is a perfectly valid syntax, but that will raise KeyError here. (10, )是一种完全有效的语法,但这会引发KeyError To get the desired output you'll have to use a loop here: 为了获得所需的输出,您必须在此处使用循环:

>>> d = {(4, 7): 0, (2, 6): 1, (10, 4): 1, (5, 11): 1, (4, 5): 1,
... (2, 8): 0, (8, 11): 0, (10, 0): 1, (6, 11): 1, (9, 11): 1,
... (1, 9): 0, (10, 1): 0, (7, 11): 1, (0, 9): 1, (3, 7): 1,
... (10, 3): 1, (10, 2): 1}
>>> [k[1] for k, v in d.items() if k[0] == 10 and v == 1]
[4, 0, 3, 2]

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

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