【问题标题】:How to move a key value in a dictionary list one level up in python如何在python中将字典列表中的键值向上移动一级
【发布时间】:2021-01-05 17:25:27
【问题描述】:

使用 Python3,我正在尝试将字典列表中的键值对向上移动。

我有一个名为 product 的变量,它具有以下内容:

    [ 
    {'color': 'red', 
     'shape': 'round', 
     'extra': {'price': 'large', 
               'onsale': 'yes',
               'instock: 'yes'}
    }, 
    {'color': 'blue', 
     'shape': 'square', 
     'extra': {'price': 'small', 
               'onsale': 'no',
               'instock: 'yes'}
    }
    ]

我想将“instock”的键值对在 extra 上移一级,以与颜色、形状、extra 保持一致 - 所以这个:

    [ 
    {'color': 'red', 
     'shape': 'round', 
     'extra': {'price': 'large', 
               'instock: 'yes'},
     'onsale': 'yes'
    }, 
    {'color': 'blue', 
     'shape': 'square', 
     'extra': {'price': 'small', 
               'onsale': 'no'},
     'instock: 'yes'
    }
    ]

我尝试使用在此处找到的以下代码:

    result = {}
    for i in products:
        if i["href"] not in result:
            result[i["selection_id"]] = {'selection_id': i["selection_id"], 'other_data':                         i["other_data"], 'value_dict': []}
        result[i["selection_id"]]["value_dict"].append({'value': i["value"], "value_name": i["value_name"]})

这对我不起作用。

如果我能在网上找到任何帮助或其他文献,我们将不胜感激!

【问题讨论】:

  • “它不起作用” 为什么不呢,出了什么问题?你没有得到想要的输出吗?代码根本没有运行吗?是不是中途出错了?当您寻求调试帮助时,您提供的相关详细信息越多越好。
  • 对于初学者来说,它给了我一个 KeyError: 'onsale'。但正如上面的代码所示,我在列表中有 onsale。其次,我找到的这段代码是为我找到的类似问题提供的解决方案,不完全是我想要的,但我认为这是一个很好的起点。

标签: python python-3.x list dictionary scripting


【解决方案1】:
products = [
    {'color': 'red', 
     'shape': 'round', 
     'extra': {'price': 'large', 
               'onsale': 'yes',
               'instock': 'yes'}
    }, 
    {'color': 'blue', 
     'shape': 'square', 
     'extra': {'price': 'small', 
               'onsale': 'no',
               'instock': 'yes'}
    }
    ]
    
    
result_list = []    
result = {}
    
for item in products:
    for key,values in item.items():
        if isinstance(values,dict):
            for inner_key, inner_value in values.items():
                #remove me if you want all of the inner items to level-up
                if inner_key == "instock":
                    result[inner_key] = inner_value
        else:
            result[key] = values
            
    result_list.append(result)


print (result_list)

输出:

[{'color': 'blue', 'shape': 'square', 'instock': 'yes'}, {'color': 'blue', 'shape': 'square', 'instock': 'yes'}]

添加注释以阐明在哪里修改,以防您希望其他键也升级

【讨论】:

  • 您好,这几乎奏效了 - 它不包括第一个 (color:blue) 与 (color:blue) 和 (color;red) 两者我希望这两个元素都会更新。
  • 那是因为字典中的键是唯一的。将它们中的每一个作为列表项插入解决了它
【解决方案2】:
lst = [ 
    {'color': 'red', 
     'shape': 'round', 
     'extra': {'price': 'large', 
               'onsale': 'yes',
               'instock': 'yes'}
    }, 
    {'color': 'blue', 
     'shape': 'square', 
     'extra': {'price': 'small', 
               'onsale': 'no',
               'instock': 'yes'}
    }
]

for d in lst:
    d['instock'] = d['extra'].pop('instock')

# pretty print on screen:
from pprint import pprint
pprint(lst)

打印:

[{'color': 'red',
  'extra': {'onsale': 'yes', 'price': 'large'},
  'instock': 'yes',
  'shape': 'round'},
 {'color': 'blue',
  'extra': {'onsale': 'no', 'price': 'small'},
  'instock': 'yes',
  'shape': 'square'}]

或者你可以使用:

d['extra'].pop('instock', 'no')

如果没有instock 键(在这种情况下默认值为no

【讨论】:

    【解决方案3】:

    非常简单:遍历列表。对于每个字典,将“extra”.“instock”复制上一级并删除原始:

    for outer_dict in product:
        outer_dict["instock"] = outer_dict["extra"]["instock"]
        del outer_dict["extra"]["instock"]
    
    for outer_dict in product:
        print(outer_dict)
    

    输出:

    {'color': 'red', 'shape': 'round', 'extra': {'price': 'large', 'onsale': 'yes'}, 'instock': 'yes'}
    {'color': 'blue', 'shape': 'square', 'extra': {'price': 'small', 'onsale': 'no'}, 'instock': 'yes'}
    

    【讨论】:

      猜你喜欢
      • 2019-10-03
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      相关资源
      最近更新 更多