Python 3:创建多个字典的列表具有相同的键,但来自多个列表的值不同

问题描述 投票:1回答:1

我正在使用来自lxml库的xpath通过XML响应进行解析。我正在获取结果并从中创建列表,如下所示:

object_name = [o.text for o in response.xpath('//*[name()="objectName"]')]
object_size_KB = [o.text for o in response.xpath('//*[name()="objectSize"]')]

我想使用列表为列表中的每个元素创建一个字典,然后将它们添加到最终列表中,如下所示:

[{'object_name': 'file1234', 'object_size_KB': 9347627},
{'object_name': 'file5671', 'objeobject_size_KBt_size': 9406875}]

我想要一个生成器,因为将来可能需要从响应中搜索更多的元数据,所以我希望我的代码可以成为将来的证明并减少重复:

meta_names = {
'object_name': '//*[name()="objectName"]',
'object_size_KB': '//*[name()="objectSize"]'
             }
def parse_response(response, meta_names):
"""
input: response: api xml response text from lxml xpath
input: meta_names: key names used to generate dictionary per object
return: list of objects dictionary
"""
    mylist = []
   # create list of each xpath match assign them to variables
    for key, value in meta_names.items():
        mylist.append({key: [o.text for o in response.xpath(value)]})
    return mylist

但是函数给了我这个:

[{'object_name': ['file1234', 'file5671']}, {'object_size_KB': ['9347627', '9406875']}]

我一直在论坛中搜索类似的案例,但找不到符合我需要的内容。感谢您的帮助。

python list dictionary dictionary-comprehension
1个回答
0
投票
我认为这就是您想要的。
© www.soinside.com 2019 - 2024. All rights reserved.