python - 我想从嵌套字典中提取特定的键、值?
问题描述
{'images': [{'id': 124,
'file_name': '124.jpg',
'height': 800,
'width': 800,
'license': 1},
{'id': 125,
'file_name': '125.jpg',
'height': 800,
'width': 800,
'license': 1},
{'id': 126,
'file_name': '126.jpg',
'height': 800,
'width': 800,
'license': 1},....
从这本字典中,我只想从整个字典中提取“id”和“file_name”我尝试了一些方法,但每次都得到一个空列表......如何提取?请纠正我!
temp = "id"
res = [val[temp] for key, val in data.items() if temp in val]
# printing result
print("The extracted values : " + str(res))
解决方案
要获得明智的价值id
,file_name
然后使用dict
res = [{d['id']:d['file_name']} for d in data['images']]
同样,你可以把它做成一个tuple
或nested
列表
res = [[d['id'],d['file_name']] for d in data['images']]
# Output
# [{124: '124.jpg'}, {125: '125.jpg'}, {126: '126.jpg'}]
# [[124, '124.jpg'], [125, '125.jpg'], [126, '126.jpg']]
推荐阅读
- spring - Jhipster 和 Spring Security - 添加身份验证提供程序保持活动的默认 jdbcauthentication 模式
- kubernetes - 如何设置具有命名空间级别权限的 Istio 或 Linkerd(没有集群管理权限)?
- date - 如何在颤动中格式化日期时间?
- python-3.x - TensorFlow 和 pycharm 自动完成问题
- sql-server - 带输入文件的 BCP
- google-apps-script - 可安装触发器在 Apps 脚本中停止工作
- java - Selenium 脚本在弹出窗口打开时挂起并在 10 分钟后正常运行
- reactjs - React-native ComponentDidMount 未触发
- laravel - composer require 可以找到包
- ios - 使用 XIB 的导航栏中的文本字段