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

时间:2017-04-29 13:50:18

标签: python django

我通过python调用api并将此代码作为响应返回:

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

我正在努力获得丽贝卡的价值,因为我需要得到作家。 所以我写道:

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

但它给了我:

KeyError at search/15
u'job'

我怎样才能获得价值?

完整代码:

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

home.html的:

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

5 个答案:

答案 0 :(得分:4)

那是因为并非列表中的所有元素都有job密钥。

更改为:

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

答案 1 :(得分:1)

找一位作家的一个班轮。

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

找到所有作家的一个班轮。

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

答案 2 :(得分:0)

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.

如果get不存在,您需要指定key的默认值。

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

答案 3 :(得分:0)

person.get(你&#34;工作&#34;)==&#34;作家&#34;

答案 4 :(得分:0)

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

试试这个

cast [“cast”] == Key“cast”的值,后者又是Dicts的列表 并以人为单位循环每个词典