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
  • 2,609
  • 4
  • 30
  • 61
  • 4
    Don't try to modify the dictionary, just create a new one – juanpa.arrivillaga Aug 21 '21 at 19:46
  • Ad an aside, why involve floats here? – juanpa.arrivillaga Aug 21 '21 at 19:47
  • Does this answer your question? [Change the name of a key in dictionary](https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary) – Mohammad Aug 21 '21 at 19:49
  • Its unix time. Maybe int is what I need not float. Would you have a tip on how to create a new dictionary? – bbartling Aug 21 '21 at 19:49
  • When you iterating a list or dictionary, you can not change it, because your are iterating it. if you want to change anything such as key, you have to create a temp list of keys that you want to change. In your example, instead of pop. you have to save them in another list and after for loop ended, change items. good lock – Hamed_gibago Aug 21 '21 at 19:49
  • Ah thanks. That makes sense – bbartling Aug 21 '21 at 19:50

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
  • 71
  • 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,258
  • 1
  • 14
  • 22
0

try with this:

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

    test[str((float(key)/1000))] = test.pop(key)
Piero
  • 216
  • 1
  • 5
  • 17