【问题标题】:Changing the value of a nested dictionary key更改嵌套字典键的值
【发布时间】:2021-04-14 21:06:35
【问题描述】:

我有一个这种格式的嵌套字典

{'U_1003076': {'C_course-v1:TsinghuaX+34100325_X+sp': {'label': 1}, 'C_course-v1:TsinghuaX+30240243X+sp': {'label': 1}}, 'U_1019796': {'C_course-v1:TsinghuaX+30240184+sp': {'label': 1}}

如何改成这个

{'U_1003076': {'C_course-v1:TsinghuaX+34100325_X+sp': 1}, 'C_course-v1:TsinghuaX+30240243X+sp': 1}, 'U_1019796': {'C_course-v1:TsinghuaX+30240184+sp': 1}

【问题讨论】:

    标签: python list dictionary nested key


    【解决方案1】:

    我建议使用递归函数

    所以通过字典检查某个键的值是否也是字典,如果是,则再次调用该函数,否则检查该键是否为"label",然后在该值上再次调用该函数并返回它

    my_dict = {
        "U_1003076": {
            "C_course-v1:TsinghuaX 34100325_X sp": {"label": 1},
            "C_course-v1:TsinghuaX 30240243X sp": {"label": 1},
        },
        "U_1019796": {"C_course-v1:TsinghuaX 30240184 sp": {"label": 1}},
    }
    def solution(my_dict):
        if type(my_dict) is not dict: return my_dict
        for k,v in my_dict.items():
            if type(v) is dict:
                my_dict[k]=solution(v)
            elif k=="label":
                return solution(v)
        return my_dict
    
    print(solution(my_dict))
    
    {
        "U_1003076": {
            "C_course-v1:TsinghuaX 34100325_X sp": 1,
            "C_course-v1:TsinghuaX 30240243X sp": 1,
        },
        "U_1019796": {"C_course-v1:TsinghuaX 30240184 sp": 1},
    }
    

    【讨论】:

      【解决方案2】:

      您可以尝试递归方法:

      def recurse(d):
          for k, v in d.items():
              if 'label' in v.keys():
                  d[k] = v['label']
              else:
                  recurse(v)
          return d
      
      >>> d = {'U_1003076': {'C_course-v1:TsinghuaX+34100325_X+sp': {'label': 1},
           'C_course-v1:TsinghuaX+30240243X+sp': {'label': 1}},
           'U_1019796': {'C_course-v1:TsinghuaX+30240184+sp': {'label': 1}}}
      
      >>> recurse(d)
      {'U_1003076': {'C_course-v1:TsinghuaX+34100325_X+sp': 1,
        'C_course-v1:TsinghuaX+30240243X+sp': 1},
       'U_1019796': {'C_course-v1:TsinghuaX+30240184+sp': 1}}
      

      【讨论】:

        【解决方案3】:

        您可以编写一个单行列表理解来迭代嵌套的字典,并使用dict.get() 在最后一级获取“标签”键的值。

        expected = {k:{i:j.get('label') for i,j in v.items()} for k,v in nested.items()}
        print(expected)
        
        {'U_1003076': {'C_course-v1:TsinghuaX+34100325_X+sp': 1,
          'C_course-v1:TsinghuaX+30240243X+sp': 1},
         'U_1019796': {'C_course-v1:TsinghuaX+30240184+sp': 1}}
        

        使用dict.get()的好处是,如果没有找到label作为key,它会返回None而不是抛出错误。您还可以为其设置默认值,以防找不到键。更多详情here.

        【讨论】:

          猜你喜欢
          • 2018-05-23
          • 1970-01-01
          • 2022-06-13
          • 2021-07-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-07-15
          • 2021-09-04
          相关资源
          最近更新 更多