问题描述:

The following is a sample dictionary with multiple keys per value array:

test_dict = {('CA', 1): [1,2,3,4], ('MT', 45): [5,6,7,8]}

I would expect that looping over the keys with itertools would yield the tuples:

import itertools

for key, value in test_dict.iteritems():

print key

However, this yields the first item in each tuple

MT

CA

How can I access the tuple within each iteration but still have access to the values, for example:

('CA', 1)

('MT', 45)

My ultimate objective is to be able index the tuple within each iteration. For example in this example I would index the tuple and access the second tuple item:

for key, value in test_dict.iteritems():

print key[1]

1

45

网友答案:

You can use list comprehension:

lst = [k for k,v in test_dict.items()]

Output:

[('MT', 45), ('CA', 1)]

To get the elements of lst:

for i in lst:
        print (i)

Output:

('MT', 45)
('CA', 1)

...and getting the first element of the tuple:

for i in lst:
        print (i[0])

Output:

MT
CA

...or the second element of the tuple:

for i in lst:
    print (i[1])

Output:

45
1
网友答案:

Use the keys() method instead, this way:

>>> test_dict = {('CA', 1): [1,2,3,4], ('MT', 45): [5,6,7,8]}
>>> 
>>> test_dict.keys()
[('MT', 45), ('CA', 1)]
>>> for k in test_dict.keys():
    print k

('MT', 45)
('CA', 1)

Or even simply:

>>> for k in test_dict:
    print k


('MT', 45)
('CA', 1)
相关阅读:
Top