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

时间:2019-07-19 07:28:52

标签: python python-3.x dictionary

我有字典:

test={"11.67":1,"12.67":2}

我想要的输出如下:

{'11.67': {'value': '11'}, '12.67': {'value': '12}}

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

我写了这个:

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)

但是结果是错误的:

{'11.67': {'value': '12'}, '12.67': {'value': '12'}}

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

还有一个 UPDATE: 我必须使用dict_keys的 indexes 。 我必须从代​​码的那部分开始。

5 个答案:

答案 0 :(得分: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'}}

我首先将字符串转换为float,然后使用int丢弃小数部分,然后再次转换回str

Carsten's answer中很好地解释了代码中出现的问题。

答案 1 :(得分:4)

您的错误在于在循环之外声明temp_dict。这有效:

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

答案 2 :(得分:3)

问题在于,您始终引用同一对象temp_dict,因此对它的任何更改都将反映在其所有实例中。

我建议使用dict理解来解决您的问题,这会将字典的创建减少到仅一行:

final_dict = {idx: {'value': idx.split('.')[0]} for idx in test.keys()}

答案 3 :(得分:3)

尝试

>>> {i:{'value': "%d"%eval(i)} for i in {"11.67":1,"12.67":2}}
{'11.67': {'value': '11'}, '12.67': {'value': '12'}}
>>> 

{}->字典理解和旧字符串"%s"格式

答案 4 :(得分:2)

将temp_dict导入final_dict后,清除temp_dict。 GOOD_LUCK

Recipe