python - 在 for 循环中使用 f 字符串添加到字典
问题描述
我目前正在尝试做一些非常相似的事情:
for letter in ['a', 'b', 'c']:
key1 = f'{letter}_1'
key2 = f'{letter}_2'
numbers = {
key1: 1,
key2: 2
}
我希望numbers
是:{'a_1': 1, 'a_2': 2, 'b_1': 1, 'b_2': 2, 'c_1': 1, 'c_2': 2}
。相反,我得到:{'c_1': 1, 'c_2': 2}
。
我该如何生产前者?
解决方案
我认为问题在于您没有在for
循环之前初始化 dict 。
numbers = {}
for letter in ['a', 'b', 'c']:
key1 = f'{letter}_1'
key2 = f'{letter}_2'
numbers.update ({
key1: 1,
key2: 2
})
print(numbers)
推荐阅读
- java - 使用 ReplyingKafkaTemplate、@KafkaListener 和 @SendTo 的 Spring Kafka 的“没有正在处理的事务”
- git - 你的 Jenkins 工作区快满了
- django - 需要帮助配置 apache .conf 文件
- jira - 如何通过单击而不是编辑打开图像链接?
- node.js - 与 NodeJS 的承诺
- amazon-web-services - 应用 S3 存储桶策略时访问被拒绝
- db2 - 基于某些标准的 IBM DB2 Timetravel 日志记录
- java - TestNG 错误:无法运行 TestNG,获取对未定义变量surefireArgLine 的引用?
- ruby - Ruby-Squib svg 文件未完全呈现
- peoplesoft - 在 Equation Engine 中编辑提示