如何将给定数据输出为字典格式?

8dtrkrch  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(466)

我有一个值如下的字段

  1. b = [
  2. {
  3. "category": "Engineer",
  4. "name": "Anthony Test",
  5. "id": 219
  6. },
  7. {
  8. "category": "Engineer",
  9. "name": "Pete Junior",
  10. "id": 220
  11. }
  12. ]

我想得到以下格式的结果,我想消除类别,并创建一个带有id和名称的字典

  1. result = {'219': 'Anthony Test', '220': 'Pete Junior'}
mw3dktmi

mw3dktmi1#

你可以使用字典理解

  1. {i['id']: i['name'] for i in b}
ckx4rj1h

ckx4rj1h2#

试试这个

  1. b=[
  2. {
  3. "category": "Engineer",
  4. "name": "Anthony Test",
  5. "id": 219
  6. },
  7. {
  8. "category": "Engineer",
  9. "name": "Pete Junior",
  10. "id": 220
  11. }
  12. ]
  13. result = {str(i['id']): i['name'] for i in b}
  14. print(result)
  15. # result = {'220': 'Pete Junior', '219': 'Anthony Test'}
展开查看全部

相关问题