0

I am really struggling with a search of a dict in python. What I do is call an external API using the Requests package.

response = requests.get(apiurl + vnendpoint + '?page=1&per_page=0&sort=id&api_key=' + apikey)

records = response.json()

This works fine and returns the following dict:

{u'pagination': {u'per_page': 0, u'total': 187, u'page': 1}, u'data': [{u'status': u'Inactive', u'name': u'access-a37', id': u'2', u'peripheral':...

The problem is, I now want to search the data object, which is a list inside the original JSON, for an ID which may or may not be there.

x = "1"
if x in records:
    print("add")

This is the part I cannot get past. It always returns a false response, but I know the ID is there.

Am I missing something really straight forward here?

Thanks

1
  • You are searching inside the outer dict not the list. You have to access the list first. Then, you will need to check the id field in the dicts I side that list. Commented Mar 27, 2017 at 16:09

2 Answers 2

2

When you use if x in records: you're checking if the value of x ("1") itself is in records. It's not. According to your question, what is in records['data'] is a dictionary containing an item called id with the value "1". Python doesn't know it needs to look into id for you.

You have two options:

  1. Go over every item in the list, access its id item and compare it to x.
  2. Build a dictionary mapping the id item to the actual data and use that for looking up x.

Code samples:

for i in records['data']:
  if i['id'] == x:
    print('found', x)

# or

d = {}
for i in records['data']:
  d[i['id']] = i
if x in d:
  print('found', x)
Sign up to request clarification or add additional context in comments.

Comments

1

First, get the data object from records

myData=records['data']

Then search for your id in myData

x = 1
myDict = dict()
for dictionnary in myData:
      if ( dictionnary['id'] == x ):
         print ('found',x)
         myDict = dictionnary
         break

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.