简体   繁体   English

将字典中的字典中的字典中的浮点数转换为int in 字典中的列表

[英]Converting float to int in a dict in dict in list in dict

I've a dict data as below.我有一个字典数据如下。 I want to convert the float into integers.我想将浮点数转换为整数。 How do I go about it?我该怎么做 go 呢? 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":我尝试了这段代码,但我收到了这个错误“RuntimeError:迭代期间字典键发生了变化”:

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)

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)}]}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM