【问题标题】:Python - create dictionary with multiple keys and where value is also dictionaryPython - 创建具有多个键的字典,其中值也是字典
【发布时间】:2019-07-19 07:28:52
【问题描述】:

我有一本字典:

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'}}

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

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

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    你可以这样做:

    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'}}
    

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

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

    【讨论】:

    • 抱歉忘了提我必须使用索引,因为我是从那部分开始代码还有一个更新:我必须使用indexes 是dict_keys。我必须从那部分代码开始。
    • 那么它就是for key in indexes。 (而不是for key in test)。
    【解决方案2】:

    您的错误在于在循环外声明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)
    

    【讨论】:

      【解决方案3】:

      问题是你总是引用同一个对象temp_dict,因此对它的任何更改都会反映在它的所有实例中。

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

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

      【讨论】:

        【解决方案4】:

        试试,

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

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

        【讨论】:

          【解决方案5】:

          将 temp_dict 导入 final_dict 后,清除 temp_dict。 好运

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-12-07
            • 2021-12-04
            • 2011-06-09
            • 2021-03-04
            • 1970-01-01
            相关资源
            最近更新 更多