问题描述
假设我有一个Python字典,但值是一个元组:例如。
dict = {Key1:(ValX1,ValY1,ValZ1),Key2:(ValX2,ValY2,ValZ2) ,...,Key99:(ValX99,ValY99,ValY99)}
仅从元组中检索第三个值,例如。 ValZ1,ValZ2或ValZ99。
我可以使用 .iteritems()
例如:
for key,val in dict.iteritems():
ValZ = val [2]
然而,是否有更直接的方法?
理想情况下,我想按键查询字典,只返回元组中的第三个值...
eg
dict [Key1] = ValZ1
而不是我目前得到的,这是 dict [Key1] =(ValX1,ValY1,ValZ1)
不可调用...
任何建议?
只要保持索引:
>> > D = {Key1:(1,2,3),Key2:(4,5,6)}
>>> D [Key2] [2]
6
Let's say that I have a Python dictionary, but the values are a tuple:
E.g.
dict = {"Key1": (ValX1, ValY1, ValZ1), "Key2": (ValX2, ValY2, ValZ2),...,"Key99": (ValX99, ValY99, ValY99)}
and I want to retrieve only the third value from the tuple, eg. ValZ1, ValZ2, or ValZ99 from the example above.
I could do so using .iteritems()
, for instance as:
for key, val in dict.iteritems():
ValZ = val[2]
however, is there a more direct approach?
Ideally, I'd like to query the dictionary by key and return only the third value in the tuple...
e.g.
dict[Key1] = ValZ1
instead of what I currently get, which is dict[Key1] = (ValX1, ValY1, ValZ1)
which is not callable...
Any advice?
Just keep indexing:
>>> D = {"Key1": (1,2,3), "Key2": (4,5,6)}
>>> D["Key2"][2]
6
这篇关于查询Python字典从元组获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!