简体   繁体   中英

Python read tuples from dictionary

I'm stucked with reading value from my dictionary. My dictionary is like a = {(1,2):(1,2,3,4),(4,5,6,7),...} and my task is to loop value, eg,(1,2,3,4) and read value[0] and value[1], in this case, is 1 and 2.

But when I'm not sure if there is a tuple or multiple tuples in value, how can I loop the value and read the first and second value of tuple? I mean, if I use for loop directly towards a, then the result of loop is a value rather than a tuple. How could I deals with this situation? My only thinking is add if statement but I wonder if there is more efficient way. :)

You can loop over the keys in the dictionary and then pull each tuple from the dictionary and loop over those, like so:

for key in dict:
    for tuple in dict[key]:
        # whatever you want to do with tuple[0] and tuple[1]

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