Query Python dictionary to get value from tuple(查询 Python 字典以从元组中获取值)
问题描述
假设我有一个 Python 字典,但值是一个元组:
Let's say that I have a Python dictionary, but the values are a tuple:
例如
dict = {"Key1": (ValX1, ValY1, ValZ1), "Key2": (ValX2, ValY2, ValZ2),...,"Key99": (ValX99, ValY99, ValY99)}
我只想从元组中检索第三个值,例如.上例中的 ValZ1、ValZ2 或 ValZ99.
and I want to retrieve only the third value from the tuple, eg. ValZ1, ValZ2, or ValZ99 from the example above.
我可以使用 .iteritems() 来做到这一点,例如:
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...
例如
dict[Key1] = ValZ1 而不是我目前得到的,即 dict[Key1] = (ValX1, ValY1, ValZ1) 这是不可调用的...
dict[Key1] = ValZ1 instead of what I currently get, which is dict[Key1] = (ValX1, ValY1, ValZ1) which is not callable...
有什么建议吗?
推荐答案
保持索引:
>>> D = {"Key1": (1,2,3), "Key2": (4,5,6)}
>>> D["Key2"][2]
6
这篇关于查询 Python 字典以从元组中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:查询 Python 字典以从元组中获取值
基础教程推荐
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
