【问题标题】:is there a more pythonic way to handle merging a list of tuples with a list into a dictionary? [duplicate]有没有更 Pythonic 的方法来处理将元组列表与列表合并到字典中? [复制]
【发布时间】:2017-09-14 21:47:44
【问题描述】:

我正在使用 Python3,我目前正在尝试重构一些代码,特别是这看起来有点草率。现在我有一个标准的循环遍历元组列表并将它们与硬编码键配对。

    values = [
        (1, 'test1', 15.5),
        (2, 'test2', 31.67),
        (3, 'item1', 16.5),
        (4, 'bike1', 15.5),
    ]

    keys = ['id', 'name', 'price']

    items = []

    for row in values:
        items.append({'id': row[0], 'name': row[1], 'price': row[2]})

    return items

这是一篇类似的文章 More efficient way to create JSON from Python

但是我很难弄清楚如何处理我的两组数据完全不同的事实

    items = [row for row in result]
    columns = [key[0] for key in cursor.description]

    print([{key: val} for key, val in zip(columns, items)] )

我想出了这个,理论上可以浓缩成一行。但由于我的数据不是 1 对 1(即一个列表与一个元组列表),它给了我这个......

[{'id': (1, 'bike2', 15.5)}, {'name': (2, 'test', 31.67)}, {'price': (3, 'bike3', 15.5)}]

UPDATE

这是我的最终解决方案,感谢 Martijn!

items = [dict(zip([key for key in keys], row)) for row in result]

【问题讨论】:

    标签: python flask


    【解决方案1】:

    你快到了;您需要压缩单个行,而不是一次压缩所有行:

    [dict(columns, row) for row in result]
    

    但是,您可以简单地告诉sqlite 为每一行生成字典,方法是设置row_factory

    def dict_factory(cursor, row):
        return {d[0]: col for d, col in zip(cursor.description, row)}
    
    connection.row_factory = dict_factory
    

    此时您只需将光标结果作为列表返回:

    return cursor.fetch_all()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 2019-11-19
      • 2019-07-12
      • 1970-01-01
      • 2011-08-15
      • 2019-09-30
      • 2020-09-30
      相关资源
      最近更新 更多