CodeL
CodeL

Reputation: 191

how to get specific value in python dictionary?

I call an api via python and return this code as response:

        {
          "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. 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:

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

Upvotes: 0

Views: 135

Answers (5)

Rubixred
Rubixred

Reputation: 123

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

Upvotes: 0

jin
jin

Reputation: 440

person.get(u"job") == "Writer"

Upvotes: 0

JkShaw
JkShaw

Reputation: 1947

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.

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

Upvotes: 0

EyuelDK
EyuelDK

Reputation: 3189

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']

Upvotes: 1

nik_m
nik_m

Reputation: 12086

That's because not all elements in the list have the job key.

Change to:

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

Upvotes: 4

Related Questions