简体   繁体   中英

extracting a tuple from a dictionary with a key/tuple pair

I know I'm close:

    for k in my_dictionary:
        #print (k, my_dict[k][0],my_dict[k][1])
        for v in my_dict[k]:
            print (v,my_dict[k])

results in:

tuple00('tuple00','tuple01')
tuple01('tuple00','tuple01')
tuple10('tuple10','tuple11')
tuple11('tuple10','tuple11')

The commented line will give me a better result

key0 tuple00 tuple01
key1 tuple00 tuple01

but I have to address them by the:

my_dict[k][0],my_dict[k][1]

which is ugly. Doing:

    for k in my_dict:
        for i,m in k:
            print (i,m,k)

gives as error in:

    for i,m in k:
ValueError: need more than 1 value to unpack

I know that a list comprehension is probably what I'm after, but I still can't even begin to grasp that.

I would accept an answer through loops (as above) or dict/list comprehension...

What I really want though, is to be able to select a Key value and use the tuple as a referenced pair: i and m

You can unpack using .items :

 d = {"key":("v1","v2")}

for k, (v1, v2) in d.items():
    print(k, v1, v2)

Which would print:

('key', 'v1', 'v2')

Using (v1, v2) unpacks each tuple/value .

You can do it this way:

d = {"key":("v1","v2")}

for key in d:
    print((key,) + d[key])

Unpacks to:

('key', 'v1', 'v2')

You can do this :

    for key, value in dictd.iteritems():
        print key, value[0], value[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