嵌套字典迭代

时间:2019-07-17 20:11:29

标签: python

此词典只有一个键,其值是词典列表。我只是在学习列表理解,并且已经弄清楚了如何使用下面的代码来提取名称列表,但是我无法弄清楚如何使用for循环迭代来获取名称列表。有人可以帮忙吗?

我知道列表理解更容易,这只是我通过嵌套迭代来发展自己的技能的原因。

lst_compr = [d["name"] for d in tester["info"]]

tester = {'info': [{"name": "Lauren", 'class standing': 'Junior', 'major': "Information Science"},{'name': 'Ayo', 'class standing': "Bachelor's", 'major': 'Information Science'}, {'name': 'Kathryn', 'class standing': 'Senior', 'major': 'Sociology'}, {'name': 'Nick', 'class standing': 'Junior', 'major': 'Computer Science'}, {'name': 'Gladys', 'class standing': 'Sophomore', 'major': 'History'}, {'name': 'Adam', 'major': 'Violin Performance', 'class standing': 'Senior'}]}

import json

print(json.dumps(tester, indent = 2))

lst = []
for x in tester["info"]:
  lst.append(x)

print(lst)

测试仪输出

{
  "info": [
    {
      "name": "Lauren",
      "class standing": "Junior",
      "major": "Information Science"
    },
    {
      "name": "Ayo",
      "class standing": "Bachelor's",
      "major": "Information Science"
    },
    {
      "name": "Kathryn",
      "class standing": "Senior",
      "major": "Sociology"
    },
    {
      "name": "Nick",
      "class standing": "Junior",
      "major": "Computer Science"
    },
    {
      "name": "Gladys",
      "class standing": "Sophomore",
      "major": "History"
    },
    {
      "name": "Adam",
      "major": "Violin Performance",
      "class standing": "Senior"
    }
  ]
}

电流输出

[{'name': 'Lauren', 'class standing': 'Junior', 'major': 'Information Science'}, {'name': 'Ayo', 'class standing': "Bachelor's", 'major': 'Information Science'}, {'name': 'Kathryn', 'class standing': 'Senior', 'major': 'Sociology'}, {'name': 'Nick', 'class standing': 'Junior', 'major': 'Computer Science'}, {'name': 'Gladys', 'class standing': 'Sophomore', 'major': 'History'}, {'name': 'Adam', 'major': 'Violin Performance', 'class standing': 'Senior'}]

预期产量

['Lauren', 'Ayo', 'Kathryn', 'Nick', 'Gladys', 'Adam']

1 个答案:

答案 0 :(得分:1)

lst = []
for x in tester["info"]:
  lst.append(x["name"])

print(lst)

代码中的问题是x引用了您迭代的每个dict项目。您只需附加x,而不是x中的“名称”值。附加x['name']可以解决此问题