python - 如何在Python的嵌套字典中获取具有相同键的所有值?
问题描述
我有一个嵌套字典mydict = {'Item1': {'name': 'pen', 'price': 2}, 'Item2': {'name': 'apple', 'price': 0.69}}
。如何获取同一个键的所有值?例如,我想得到一个[2, 0.69]
与 key 对应的列表'price'
。不使用循环的最佳方法是什么?
解决方案
我怀疑实际上没有任何循环是可能的,所以这里有一个使用列表理解的解决方案:
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]
推荐阅读
- javascript - Discord JS自我昵称命令
- docker - 连接到redis docker容器时出错
- node.js - 如何在 typegoose 中使用更新的钩子?
- sql - 如何使用“SELECT FOR UPDATE”锁定一组行
- arrays - 在 JavaScript 中使用数组时确定效率(大 O 表示法)
- sql-server - 如何区分 SQL Server 中的 2 个阿拉伯字母
- python - 编写一个程序,首先读取输入文件的名称,然后是两个字符串,表示搜索范围的下限和上限
- java - 设置 iText 文档的 BackgroundColor
- javascript - 在本机反应中显示来自firebase的图像(命中错误)
- video - ffmpeg 缩放 4k 视频并添加字幕