pythonic 方法将字典展平或扩展为 python 中的字典列表

Inq*_*abi 1 python dictionary python-3.x

我有一本字典,其值为列表对象。

{'a': [1, 2, 3], 'b': [4, 5, 6]}
Run Code Online (Sandbox Code Playgroud)

我想将字典扩展为以下内容(由于缺乏正确的词):

 [{'a': 1, 'b': 4}, {'a': 2, 'b': 5}, {'a': 3, 'b': 6}]
Run Code Online (Sandbox Code Playgroud)

我有一个解决方案,对我来说看起来有点非Pythonic、丑陋和hackish。

def flatten_dict(d: dict) -> list[dict]:
    """
    get [{'a': 1, 'b': 4}, {'a': 2, 'b': 5}] from {'a': [1, 2], 'b': [4, 5]}

    :param d: dict object
    :return: list of dicts
    """
    values = list(d.values())
    val_zip = list(zip(*values))

    keys = [list(d.keys())] * len(values[0])

    bonded_vals = list(zip(keys, val_zip))
    return list(map(lambda p: dict(zip(p[0], p[1])), bonded_vals))
Run Code Online (Sandbox Code Playgroud)

请帮助/指导我找到一个合适的 Python 功能,该功能可以执行类似的操作并提高代码的可读性。

And*_*ely 6

你可以试试:

dct = {"a": [1, 2, 3], "b": [4, 5, 6]}

out = [dict(zip(dct, t)) for t in zip(*dct.values())]
print(out)
Run Code Online (Sandbox Code Playgroud)

印刷:

[{'a': 1, 'b': 4}, {'a': 2, 'b': 5}, {'a': 3, 'b': 6}]
Run Code Online (Sandbox Code Playgroud)