如何在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'}

    }

    ]

我想将 extra 内的“instock”键值对移至上一级,以与颜色、形状、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"]})

这对我不起作用。


我可以在网上找到的任何帮助或其他文献将不胜感激!


慕桂英3389331
浏览 92回答 3
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'}

aluckdog

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 pprintpprint(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

qq_花开花谢_0

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'}]添加注释以澄清在哪里修改,以防您也希望其他键升级
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python