简体   繁体   English

从具有键/元组对的字典中提取元组

[英]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 我真正想要的是能够选择一个Key值并将元组用作引用对: im

You can unpack using .items : 您可以使用.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 . 使用(v1, v2)解压缩每个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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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