0

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?

Albatross
  • 955
  • 1
  • 7
  • 13
  • 4
    You're re-initialising the dictionary within the loop. You need to declare the dictionary outside of the loop and then add values to it – PeptideWitch Nov 25 '19 at 23:28

4 Answers4

2

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)
Magofoco
  • 5,098
  • 6
  • 35
  • 77
  • Ah that's it. I had tried initialising previously, but that doesn't fix it by itself. The `numbers.update` was the key I was missing. Thanks! – Albatross Nov 25 '19 at 23:33
1

You could try doing something like this

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

You need to initialize your dictionary outside the for-loop. In your code, you're creating a new dictionary with each iteration.

Rod Xavier
  • 3,983
  • 1
  • 29
  • 41
1

You are creating a new object every loop.

numbers = {}

for letter in ['a', 'b', 'c']: 
    key1 = f'{letter}_1' 
    key2 = f'{letter}_2' 
    numbers.update({ 
        key1: 1, 
        key2: 2 
    })
Sraw
  • 18,892
  • 11
  • 54
  • 87
0

You could, if desired, build it with a dict comprehension as:

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

Which gives:

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

It's a bit hard to read but not too bad.

neutrino_logic
  • 1,289
  • 1
  • 6
  • 11
  • That's a nice one-liner. Unfortunately my actual usage has a few extra steps in the loop that would blow this up into full unreadable territory. – Albatross Nov 25 '19 at 23:41