简体   繁体   中英

How to get keys and values in dictionary, if key and value is tuple

I have dict A and list B . Actually keys of A is x and y which define location, and value of A is index of object in B .

A = {(9, 10): (0, 2, 3), (2, 5): (6, 4, 1), (3, 7): (5, 7, 1)}
B = ['cat', 'fish', 'snack', 'duck', 'mouse', 'pig', 'bird', 'rabbit']

I want to print that point (9,10) has object in B index [0] , [2] , [3]

(9,10) : cat, snack, duck
(2,5)  : bird,mouse,fish
(3,7)  : pig, rabbit,fish

Create a mapping with the index and the corresponding value as a dictionary, like this

mapping = {idx: item for idx, item in enumerate(B)}

or simply

mapping = dict(enumerate(B))

then you can simply pick corresponding values from mapping , like this

for key, values in A.iteritems():
  print("{}: {}".format(key, ", ".join(mapping[value] for value in values)))

Output

(9, 10): cat, snack, duck
(3, 7): pig, rabbit, fish
(2, 5): bird, mouse, fish

You can access the dictionary with the tuple. Then you can generate a new list with the indexes returned.

print [B[location] for location in A[(9, 10)]]

# ['cat', 'snack', 'duck']

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