如何在 python 中将字典列表中的键值向上移动一级

How to move a key value in a dictionary list one level up in python

使用 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”的键值对向上移动一级,以便与颜色、形状等保持一致 - 所以:

    [ 
    {'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"]})

它对我不起作用。

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

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

添加了注释以阐明在您希望其他键也为 level-up 时修改的位置

非常简单:遍历列表。对于每个字典,将“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'}
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