首页 > 解决方案 > 如何在Python的嵌套字典中获取具有相同键的所有值?

问题描述

我有一个嵌套字典mydict = {'Item1': {'name': 'pen', 'price': 2}, 'Item2': {'name': 'apple', 'price': 0.69}}。如何获取同一个键的所有值?例如,我想得到一个[2, 0.69]与 key 对应的列表'price'。不使用循环的最佳方法是什么?

标签: pythonpython-3.xdictionary

解决方案


我怀疑实际上没有任何循环是可能的,所以这里有一个使用列表理解的解决方案:

mydict = {'Item1': {'name': 'pen', 'price': 2}, 'Item2': {'name': 'apple', 'price': 0.69}}
output = [v["price"] for v in mydict.values()]
print(output)

或使用以下解决方案map

output = list(map(lambda v: v["price"], mydict.values()))
print(output)

所有输出:

[2, 0.69]

推荐阅读