Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda