繁体   English   中英

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

[英]Python 3: Creating list of multiple dictionaries have same keys but different values coming from multiple lists

我正在使用 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

然而 function 给了我这个:

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

我一直在论坛中寻找类似的案例,但找不到符合我需求的东西。 感谢你的帮助。

更新: Renneys 的答案是我想要的我刚刚调整了结果范围的长度值,因为我并不总是每个 object 键的 xpath 的长度相同,而且每次我选择第一个索引 [0] 时我的列表都有相同的长度。 现在 function 看起来像这样。

def create_entries(root, keys):
    tmp = []
    for key in keys:
        tmp.append([o.text for o in root.xpath('//*[name()="' + key + '"]')])
    ret = []
    # print(len(tmp[0]))
    for i in range(len(tmp[0])):
        add = {}
        for j in range(len(keys)):
            add[keys[j]] = tmp[j][i]
        ret.append(add)
    return ret

我想这就是你要找的。

您可以使用 zip 将您的两个列表组合成一个值对列表。
然后,您可以使用列表推导式或生成器表达式将值对与所需的键配对。

import pprint

object_name = ['file1234', 'file5671']
object_size = [9347627, 9406875]

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

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

# List Comprehension
obj_list = [{'object_name': name, 'object_size': size} for name,size in zip(object_name,object_size)]

pprint.pprint(obj_list)
print('\n')


# Generator Expression
generator = ({'object_name': name, 'object_size': size} for name,size in zip(object_name,object_size))

for obj in generator:
  print(obj)

实时代码示例 -> https://onlinegdb.com/SyNSwd7jU


我认为接受的答案更有效,但这里有一个如何使用列表推导的示例。

meta_names = {
'object_name': ['file1234', 'file5671'],
'object_size_KB': ['9347627', '9406875'],
'object_text': ['Bob', 'Ross']
             }

def parse_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
  """
  # List comprehensions
  to_dict = lambda l: [{key:val for key,val in pairs} for pairs in l]

  objs = list(zip(*list([[key,val] for val in vals] for key,vals in meta_names.items())))

  pprint.pprint(to_dict(objs))  

parse_response(meta_names)

实时代码-> https://onlinegdb.com/ryLq4PVjL

使用二维数组:

def createEntries(root, keys):
    tmp = []
    for key in keys:
        tmp.append([o.text for o in root.xpath('//*[name()="' + key + '"]')])
    ret = []
    for i in range(len(tmp)):
        add = {}
        for j in range(len(keys)):
            add[keys[j]] = tmp[j][i]
        ret.append(add)
    return ret

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM