Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda