首页 > 解决方案 > 我想从嵌套字典中提取特定的键、值?

问题描述

{'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))  

标签: pythondictionary

解决方案


要获得明智的价值idfile_name然后使用dict

res = [{d['id']:d['file_name']} for d in data['images']]

同样,你可以把它做成一个tuplenested列表

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']]

推荐阅读