简体   繁体   English

如何在python字典中获取特定值?

[英]how to get specific value in python dictionary?

I call an api via python and return this code as response: 我通过python调用了一个api并返回以下代码作为响应:

        {
          "cast": [
            {
              "character": "Power",
              "name": "George"
            },
            {
              "character": "Max",
              "job": "Sound",
              "name": "Jash"
            },
            {
              "character": "Miranda North",
              "job": "Writer",
              "name": "Rebecca"
            }
          ]
        }

I am trying to get the value of Rebecca because i need to get the Writer. 我试图获取Rebecca的价值,因为我需要获取Writer。 So i wrote: 所以我写道:

for person in cast # cast is the variable keeps whole code above NOT inside the dict:
    if person["job"] == "Writer":
        writer = person["name"]

but it gives me: 但这给了我:

KeyError at search/15
u'job'

how can i get the value? 我如何获得价值?

FULL CODE: 完整代码:

writer = ""
for person in api['cast']:
    if person.get('job') == 'Writer':
        writer = person.get('name')
return render(request, 'home.html', {
    'writer': writer
})

home.html: home.html:

<p>{{writer}}</p>

That's because not all elements in the list have the job key. 这是因为并非列表中的所有元素都具有job密钥。

Change to: 改成:

for person in cast #whole code above:
    if person.get('job') == 'Writer':
        writer = person.get('name')

One liner to find one writer. 一线找到一位作家。

writer = next((person for person in api['cast'] if person.get('job') == 'Writer'), None)

One liner to find all writers. 一个班轮找到所有作家。

writers = [person for person in api['cast'] if person.get('job') == 'Writer']
Syntax for dictionary get() method:

dict.get(key, default=None)

Parameters
    key: This is the Key to be searched in the dictionary.
    default: This is the Value to be returned in case key does not exist.

You need to specify the default value for get in case the key doesn't exist. 您需要指定get的默认值,以防key不存在。

>>> for person in api['cast']:
...   if person.get('job', '') == 'Writer':
...     writer = person.get('name')

person.get(u“ job”)==“作家”

for person in cast["cast"]: # cast is the variable keeps whole code above NOT inside the dict if person["job"] == "Writer": writer = person["name"]

try this 尝试这个

cast["cast"] == Value of Key "cast" , which in turn is list of Dicts and for looping through each Dictionary as person cast [“ cast”] ==键“ cast”的值,该值又是字典列表,并以个人的身份循环遍历每个字典

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM