从列表中嵌套的字典中获取特定键的值。

huangapple go评论77阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年6月22日 15:18:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529417.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定