Finding and replacing a value in a Python dictionary(在 Python 字典中查找和替换值)
问题描述
我是 stackoverflow 的完全新手,所以如果我最终将其发布在错误的地方(或任何其他与新手相关的 mitakes!谢谢!),请原谅我.
I'm a complete newbie to stackoverflow, so please excuse me if I end up posting this in the wrong place (or any other newbie-related mitakes! Thanks!).
我的问题与 Python 3.x 有关,我试图在其中基本上访问一个非常小的字典中的一个值(3 个键,每个 1 个值).我在网上(和这里)搜索了高和低,但似乎找不到与替换字典中的值有关的任何内容.我找到了替换"功能,但似乎不适用于字典.
My question pertains to Python 3.x, where I am trying to basically access a value in a very small dictionary (3 keys, 1 value each). I have searched high and low on the web (and on here), but cannot seem to find anything pertaining to replacing a value in a dictionary. I have found the "replace" function, but does not seem to work for dictionaries.
所以,这是我的字典:
a1 = {"Green": "Tree", "Red": "Rose", "Yellow": "Sunflower"}
例如,我将如何查询值Rose"以将其替换为Tulip"?
How would I go about querying the value "Rose" to replace it with "Tulip," for example?
任何帮助都将不胜感激,即使只是为我指明正确的方向!
Any help would be greatly appreciated, even if it is just to point me in the right direction!
非常感谢!
推荐答案
首先必须找到值为 "Rose"
的键:
You first must find the key that has the value "Rose"
:
for color, flower in a1.items():
if flower == "Rose":
a1[color] = "Tulip"
这篇关于在 Python 字典中查找和替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 字典中查找和替换值
基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01