英文:
getting a specific key value from a dictionary nested within a list
问题
我想从一个嵌套在列表中的字典中获取特定的键值
你好,
代码
students = [
{"name": "Hermione", "house": "Gryffindor", "patronus": "Otter"},
{"name": "Harry", "house": "Gryffindor", "patronus": "Stag"},
{"name": "Ron", "house": "Gryffindor", "patronus": "Jack Russell terrier"},
{"name": "Draco", "house": "Slytherin", "patronus": None}
]
任何帮助将不胜感激。
我尝试过这个
next(item["patronus"] for item in students if item["patronus"] == "Stag")
但这给了我以下结果
"Stag"
我期望的是
Stag
英文:
I want to get a specific key value from a dictionary nested within a list
Hello,
**Code **
students = [
{"name": "Hermione", "house": "Gryffindor", "patronus": "Otter"},
{"name": "Harry", "house": "Gryffindor", "patronus": "Stag"},
{"name": "Ron", "house": "Gryffindor", "patronus": "Jack Russell terrier"},
{"name": "Draco", "house": "Slytherin", "patronus": None}
Any help would be appreciated.
**I tried this **
next (item for item in students if item ["patronus"] == "Stag")
But this get me the following
{"name": "Harry", "house": "Gryffindor", "patronus": "Stag"},
What i expect
Stag
答案1
得分: 0
尽管这个问题没有意义。但这里有一个解决方案供您参考。
因为您正在请求项(这是完整的字典),所以您得到了完整的行/字典,如果您只想要 "stag",您必须请求那个特定的键。
x = [i["patronus"] for i in students if i.get("patronus") == 'Stag']
print(x[0] if x else None)
英文:
Although the problem doesn't make sense.But here is a solution for you.
You are getting complete row/dict because you are asking for item(thats the complte dict) , if you just want the stag, you have to ask for that particular key.
x=[i["patronus"] for i in students if i.get("patronus")=='Stag']
print(x[0] if x else None)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论