2014-11-23 117 views
1

我使用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} 

出於某種原因,我想獲得在元組第二個數字: 第一號== 10 值== 1

我試着用(10,)訪問字典,但我認爲這種語法是不允許在Python中。

答案應該是:[4 ,0 ,3 , 2]

+2

'1'不應該是結果的一部分,應該嗎? – 2014-11-23 10:48:02

+0

是的,謝謝:) – 2014-11-23 10:51:03

回答

6

你必須遍歷字典,例如:

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] 
1
result=[] 
for key in your_dict.keys(): 
    if key[0]==10 and your_dict[key]==1: 
    result.append(key[1]) 
1

(10,)是一個完全有效的語法,但是這將提高KeyError這裏。要獲得所需的輸出,您必須在此使用循環:

>>> 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]