Search code examples
pythonpython-3.xloopsdictionaryf-string

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


I'm currently trying to do something very similar to:

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

I would expect numbers to be: {'a_1': 1, 'a_2': 2, 'b_1': 1, 'b_2': 2, 'c_1': 1, 'c_2': 2}. Instead I get: {'c_1': 1, 'c_2': 2}.

How can I go about producing the former?


Solution

  • I think the issue is that you did not initialise the dict before the for loop.

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