在 for 循环中使用 f 字符串添加到字典

Add to dictionary with an f-string inside a for loop

我目前正在尝试做一些与以下内容非常相似的事情:

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 循环之前初始化字典。

numbers = {}


for letter in ['a', 'b', 'c']:
    key1 = f'{letter}_1'
    key2 = f'{letter}_2'
    numbers.update ({
        key1: 1,
        key2: 2
    })

print(numbers)

你可以尝试这样做

numbers = {}
for letter in ['a', 'b', 'c']:
    key1 = f'{letter}_1' 
    key2 = f'{letter}_2' 
    numbers.update({ 
        key1: 1, 
        key2: 2 
    })

您需要在 for 循环之外初始化字典。在您的代码中,每次迭代都会创建一个新字典。

您在每个循环中创建一个新对象。

numbers = {}

for letter in ['a', 'b', 'c']: 
    key1 = f'{letter}_1' 
    key2 = f'{letter}_2' 
    numbers.update({ 
        key1: 1, 
        key2: 2 
    })

如果需要,您可以使用字典理解来构建它:

mydict = {f'{x}_{str(y)}':y for x in ['a','b','c'] for y in (1,2)}

给出:

{'a_1': 1, 'a_2': 2, 'b_1': 1, 'b_2': 2, 'c_1': 1, 'c_2': 2}

有点难读,但还算不错。