查询Python字典以从元组中获取值
假设我有一个 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]
但是,有更直接的方法吗?
理想情况下,我想按键查询字典并仅返回元组中的第三个值...
例如
dict[Key1] = ValZ1
而不是我当前得到的,即 dict[Key1] = (ValX1, ValY1, ValZ1)
不可调用...
有什么建议吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需保持索引即可:
Just keep indexing:
使用元组解包:
通常会使用
如果人们只对元组中的一项感兴趣, 元组解包。但如果您将
gettext
模块用于多语言应用程序,这可能会导致问题,因为此模型设置了一个名为_
的全局函数。由于元组是不可变的,因此您无法仅设置一项,例如
您必须先解包:
Use tuple unpacking:
Often people use
if they are only interested in one item of the tuple. But this may cause problem if you use the
gettext
module for multi language applications, as this model sets a global function called_
.As tuples are immutable, you are not able to set only one item like
You have to unpack first:
使用生成器表达式!
您不需要使用 iteritems,因为您只查看值。
Using a generator expression!
You don't need to use iteritems because you're only looking at the values.