如何使用 python 和 bottle 框架从嵌套字典中获取具有相同值的元素?

How to get elements from a nested dictionary that has the same value using python and bottle framework?

我在 python 中使用 bottle 框架,我创建了一个动态的@get 路由,它获取所有基于 user_id 的推文来自 URL

的 ID

下面是我的嵌套推文字典和@get 路由

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]))

所以问题是当我像这样使用 postman 调用此路由时:

我只得到第一个带有通过 URL 传递的 id 的元素,即使我应该得到所有具有 "user_id" 的项目": "1 ".

我在 jupyter 上尝试了同样的事情,令人惊讶的是我得到了我期待的结果:

谁能告诉我我做错了什么!先感谢您。如前所述,我正在使用 python 和 bottle 框架。

当您 return 时,它会停止查找列表中的下一项。 您应该先将其存储在列表中。
试试这个

@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))

或者如果您可以使用列表理解来简化:

@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))