首页 > 解决方案 > 在 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}

我该如何生产前者?

标签: pythonpython-3.xloopsdictionaryf-string

解决方案


我认为问题在于您没有在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)

推荐阅读