在一行中从嵌套字典中解包多个值 "pythonically"

Unpacking multiple values from a nested dictionary in one line "pythonically"

假设我有一个如下所示的嵌套字典:

numbers = { 
    'one': {"square": "one", "cube": "one"},
    'two': {"square": "four", "cube": "eight"},
    'three': {"square": "nine", "cube": "twenty-seven"},
    'four': {"square": "sixteen", "cube": "sixty-four"}
}

我想将正方形和立方体解包到列表中。我可以这样做:

squares = [n["square"] for n in numbers.values()]
cubes = [n["cube"] for n in numbers.values()]

但对于重复的代码,这似乎不是很令人满意。我也可以引入 numpy 并执行此操作:

import numpy
squares_array, cubes_array = numpy.array([(n["square"],n["cube"]) for n in numbers.values()]).T

并且它巧妙地将所有内容解压缩到 numpy 数组中,但它看起来有点不令人满意,因为我不需要 numpy 来执行此操作,并且在我非常主观的意见中,最后进行转置有点奇怪。它对我来说似乎不是“pythonic”。

所以问题是如何在没有 numpy 的情况下在一行中完成此操作?

squares, cubes = zip(*[(n["square"], n["cube"]) for n in numbers.values()])

您可以使用 zip 和迭代器:

squares, cubes = map(list, zip(*(d.values() for d in numbers.values())))

如果有更多键或不同的顺序,请手动指定它们:

squares, cubes = map(list, zip(*([d['square'], d['cube']]
                                 for d in numbers.values())))

输出:

>>> squares
['one', 'four', 'nine', 'sixteen']

>>> cubes
['one', 'eight', 'twenty-seven', 'sixty-four']