Catch element using python json

Asked

Viewed 937 times

0

I’m using the following code to try to get what’s written inside definition, located in list

import requests
import json
word = "salut"
page = requests.get("http://api.urbandictionary.com/v0/define?term=" + word)
gotcha = page.json()
print(gotcha.get("list"))

Only the problem is that I can’t actually collect the string inside definition

[{'definition': 'Informal French greeting, equivalent to the English "hi."', 'permalink': 'http://salut.urbanup.com/1076339', 'thumbs_up': 186, 'author': 'WeluvTwinkie', 'word': 'Salut', 'defid': 1076339, 'current_vote': '', 'example': '"Hey, there!"\r\n"Salut!"', 'thumbs_down': 28}, {'definition': 'A sly way of pronouncing the word [slut]; used to describe pretty, [nympho] ballerinas.', 'permalink': 'http://sa-lut.urbanup.com/1152075', 'thumbs_up': 13, 'author': 'Sheeba', 'word': 'Sa-lut', 'defid': 1152075, 'current_vote': '', 'example': 'My saaaaa-lut: Scott Lloyd Forward', 'thumbs_down': 57}]
  • 1

    In the code you only got the value of list, that returns a list of dictionaries. You can edit the question and describe how you tried to access it definition, in fact?

  • As I say in the question, the problem is that I can’t get the value of Definition, I could only access the values included in the list... That is, I would like to collect the information from Definition

  • You know how to access a value in a list and in a dictionary?

  • Yes, in certain cases

  • So the return you have on gotcha.get("list") is a list with only one element, which is a dictionary. You will need to access the position in the list to get the dictionary and, in it, access the key you want.

  • Confused, but I’ll try. Thank you

  • In fact, that question is the same as this one: https://answall.com/questions/267746/como-usar-json-no-python

  • Possible duplicate of How to use JSON in Python?

Show 3 more comments

1 answer

2

In this case you have a dictionary. You can use a for to go through the array and read each item by the key. Save this list in a variable, var and prints:

for v in var: print(v['definition'])

Browser other questions tagged

You are not signed in. Login or sign up in order to post.