-5

I've a dict data as below. I want to convert the float into integers. How do I go about it? I tried a few ways but to no avail.

data:

{'ABC': {'2020-09-01': [{487.0: (0, 1), 488.0: (1, 2)}, {489.0: (0, 1), 481.0: (1, 2)}]},
'CDE': {'2020-01-01': [{484.0: (0, 1), 483.0: (1, 2)}, {482.0: (0, 1), 481.0: (1, 2)}]}}

I want this:

{'ABC': {'2020-09-01': [{487: (0, 1), 488: (1, 2)}, {489: (0, 1), 481: (1, 2)}]},
'CDE': {'2020-01-01': [{484: (0, 1), 483: (1, 2)}, {482: (0, 1), 481: (1, 2)}]}}

I tried this code, but I get this error "RuntimeError: dictionary keys changed during iteration":

for i in data:
    for date in data[i]:
        for model in range(0, len(data[i][date])):
            for k, v in data[i][date][model].items():
                data[i][date][model][int(k)] = data[i][date][model].pop(k)
lol23
  • 1
  • 1
  • 2
    You say you made multiple attempts, to no avail. Post a [MCVE] of the attempt you think most likely to be close to correct, and we'll help you fix it. Don't just ask us to write all your code for you. – ShadowRanger Mar 24 '21 at 01:57
  • How would you solve the problem if you just had `{487.0: (0, 1), 488.0: (1, 2)}, {489.0: (0, 1), 481.0: (1, 2)}`? How can you find dicts like that in your overall data structure? Now, knowing those two things, can you think of a way to solve the overall problem? – Karl Knechtel Mar 24 '21 at 02:02
  • 1
    https://stackoverflow.com/questions/11941817/how-to-avoid-runtimeerror-dictionary-changed-size-during-iteration-error – pptaszni Mar 24 '21 at 10:21

1 Answers1

0

I think your code is close but, as you say, you modified the dictionary keys during iteration. Here's one way to build the intermediate replacement values.

d = {
    "ABC": {
        "2020-09-01": [{487.0: (0, 1), 488.0: (1, 2)}, {489.0: (0, 1), 481.0: (1, 2)}]
    },
    "CDE": {
        "2020-01-01": [{484.0: (0, 1), 483.0: (1, 2)}, {482.0: (0, 1), 481.0: (1, 2)}]
    },
}

print('d before:', d)

for k1,v1 in d.items():
    for k2,v2 in v1.items():
        v1[k2] = [{int(k4): v4 for k4,v4 in v3.items()} for v3 in v2]

print('d after:', d)

Results:

d before: {'ABC': {'2020-09-01': [{487.0: (0, 1), 488.0: (1, 2)}, {489.0: (0, 1), 481.0: (1, 2)}]}, 'CDE': {'2020-01-01': [{484.0: (0, 1), 483.0: (1, 2)}, {482.0: (0, 1), 481.0: (1, 2)}]}}
d after: {'ABC': {'2020-09-01': [{487: (0, 1), 488: (1, 2)}, {489: (0, 1), 481: (1, 2)}]}, 'CDE': {'2020-01-01': [{484: (0, 1), 483: (1, 2)}, {482: (0, 1), 481: (1, 2)}]}}
jarmod
  • 71,565
  • 16
  • 115
  • 122