0

If I have a dictionary like this below:

test = {'1629417600000': {'Payload': 1},
         '1629418500000': {'Payload': 2},
         '1629419400000': {'Payload': 3},
         '1629420300000': {'Payload': 4},
         '1629421200000': {'Payload': 5},
         '1629422100000': {'Payload': 6},
         '1629423000000': {'Payload': 7},
         '1629423900000': {'Payload': 8},
         '1629424800000': {'Payload': 9},
         '1629425700000': {'Payload': 10}}

How can I modify the dictionary key names? I am trying to keep the same name but divide as a float by 1000.

This will throw an RuntimeError: dictionary keys changed during iteration below. Any tips greatly appreciated.

for key in test.keys():
    test[str((float(key)/1000))] = test.pop(key)
bbartling
  • 3,288
  • 9
  • 43
  • 88

3 Answers3

3

Try this?

test = {key.removesuffix("000"): value for key, value in test.items()}

However note that this does not modify test in-place, but rather creates a new dictionary, and then assign the new dictionary to test.

Alternatively, a minor change to your original code would fix it:

for key in list(test.keys()):
    test[str((float(key)/1000))] = test.pop(key)

This works because the list(test.keys()), that is being iterated, does not change during the iteration since it is created before the iteration starts and does not depend on the change of test later on.

Z Che
  • 69
  • 3
1

You can use a dictionary comprehension to create a new dictionary with the updated keys you desire:

test = {str(int(k) // 1000): v for k, v in test.items()}
Zachary Cross
  • 2,298
  • 1
  • 15
  • 22
0

try with this:

for key in list(test.keys()):

    test[str((float(key)/1000))] = test.pop(key)
Piero
  • 404
  • 3
  • 7
  • 22