简体   繁体   中英

Work with tuples as dictionary keys

I use GraphViz library and in some case, it retuns me a dictionary having tuple as keys.

{(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

I've tried to access the dictionary with (10, ) but I think this syntax is not allowed in python.

the answer should be : [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. 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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