查询Python字典以从元组中获取值

发布于 2024-12-05 16:05:26 字数 544 浏览 1 评论 0原文

假设我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雨落星ぅ辰 2024-12-12 16:05:26

只需保持索引即可:

>>> D = {"Key1": (1,2,3), "Key2": (4,5,6)}
>>> D["Key2"][2]
6

Just keep indexing:

>>> D = {"Key1": (1,2,3), "Key2": (4,5,6)}
>>> D["Key2"][2]
6
碍人泪离人颜 2024-12-12 16:05:26

使用元组解包:

for key, (valX, valY, valZ) in dict.iteritems():
       ...

通常会使用

for key, (_, _, valZ) in dict.iteritems():
       ...

如果人们只对元组中的一项感兴趣, 元组解包。但如果您将 gettext 模块用于多语言应用程序,这可能会导致问题,因为此模型设置了一个名为 _ 的全局函数。

由于元组是不可变的,因此您无法仅设置一项,例如

d[key][0] = x

您必须先解包:

x, y, z = d[key]
d[key] = x, newy, z

Use tuple unpacking:

for key, (valX, valY, valZ) in dict.iteritems():
       ...

Often people use

for key, (_, _, valZ) in dict.iteritems():
       ...

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

d[key][0] = x

You have to unpack first:

x, y, z = d[key]
d[key] = x, newy, z
影子是时光的心 2024-12-12 16:05:26

使用生成器表达式!

for val in (x[2] for x in dict):
    print val

您不需要使用 iteritems,因为您只查看值。

Using a generator expression!

for val in (x[2] for x in dict):
    print val

You don't need to use iteritems because you're only looking at the values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文