Home > Enterprise >  How to get elements from a nested dictionary that has the same value using python and bottle framewo
How to get elements from a nested dictionary that has the same value using python and bottle framewo

Time:03-20

I am working with bottle framework in python, and I have created a dynamic @get route that gets all tweets with the same user_id based on the ID from the URL

Below is my nested tweets dictionary and the @get route

tweets= {
    "1" : {"user_id":"1", "name": "a", "email": "a@"}, 
    "2": {"user_id":"1", "name": "b", "email": "b@"},
    "3": {"user_id":"1", "name": "b", "email": "b@"},
    "4": {"user_id":"2", "name": "c", "email": "c@"},
}


@get('/user-tweets/<user_id>')
def _(user_id):
    
   for key in tweets:
      if user_id in tweets[key]['user_id']:
           
          response.content_type = 'application/json; charset=UTF-8'
          return json.dumps(dict(tweets=tweets[key]))

So the problem is when I call this route using postman like this:

enter image description here

I get only the first element with the id that was passed through the URL, even though I should get all the items that have "user_id": "1".

enter image description here

I tried the same exact thing on jupyter and surprisingly I got the results that I was expecting:

enter image description here

Can someone please tell me what I am doing wrong here! Thank you in advance. As mentioned before, I am using python with bottle framework.

CodePudding user response:

When you return it stops finding the next items in your list. You should store it in a list first.
try this

@get('/user-tweets/<user_id>')
def _(user_id):
    user_tweets = []
    for key in tweets:
        if user_id in tweets[key]['user_id']
            user_tweets.append(tweets[key])
    response.content_type = 'application/json; charset=UTF-8'
    return json.dumps(dict(tweets=user_tweets))

or if you can simplify by using list comprehension:

@get('/user-tweets/<user_id>')
def _(user_id):
    user_tweets = [tweets[key] for key in tweets if user_id in tweets[key]['user_id']]
    response.content_type = 'application/json; charset=UTF-8'
    return json.dumps(dict(tweets=user_tweets))
  • Related