Python-创建具有多个键的字典,其中值也是字典

Dej*_*jan 3 python dictionary python-3.x

我有一本字典:

test={"11.67":1,"12.67":2}
Run Code Online (Sandbox Code Playgroud)

我想要的输出如下:

{'11.67': {'value': '11'}, '12.67': {'value': '12}}
Run Code Online (Sandbox Code Playgroud)

对键进行拆分时,第二个字典中的值是第一个索引。

我这样写:

test={"11.67":1,"12.67":2}
indexes=test.keys()
final_dict={}
temp_dict={}
for index in indexes:
    b=index.split('.')[0]
    temp_dict['value']=b;
    final_dict.update({index:temp_dict})
print (final_dict)
Run Code Online (Sandbox Code Playgroud)

但是结果是错误的:

{'11.67': {'value': '12'}, '12.67': {'value': '12'}}
Run Code Online (Sandbox Code Playgroud)

不知道出了什么问题。谢谢

还有一个更新: 我必须使用 dict_keys 索引。我必须从代​​码的那部分开始。

hir*_*ist 5

您可以这样做:

test = {"11.67": 1, "12.67": 2}
res = {key: {"value": str(int(float(key)))} for key in test}
# {'11.67': {'value': '11'}, '12.67': {'value': '12'}}
Run Code Online (Sandbox Code Playgroud)

在这里,我首先将字符串转换为floats,然后通过使用丢弃小数部分intstr再次转换回。

Carsten的答案很好地解释了代码中出错的地方