Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
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>
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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')
over 4 years ago · Santiago Trujillo Report

0

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']
over 4 years ago · Santiago Trujillo Report

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.

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')
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!