从嵌套列表中获取不同的列表

时间:2016-02-04 15:50:16

标签: python dictionary flask

我是来自javascript / nodeJS培养的Python新手。我有一个带有嵌套列表的python字典,我在访问时遇到了很多麻烦。我需要拉出嵌套列表,以便检查唯一的电子邮件。以下是我的GET请求撤回的内容:

{"data": [{"login_date": "2014-04-17T19:14:29+08:00", "email": "walter.elwyn@yahoo.com"}, {"login_date": "2014-04-22T09:31:56+04:00", "email": "helyn67@cruickshankmckenzie.com"}]

返回的实际数据字典要长得多,但你明白了......所以我有两个问题:

  1. 如何通过电子邮件在内容词典中访问特定点

  2. 如何在字典中循环播放独特的电子邮件?

  3. 这是我的代码:

    from flask import Flask
    import requests
    import urllib2
    app = Flask(__name__)
    
    
    @app.route('/')
    def hello_world():
        content = urllib2.urlopen('https://9g9xhayrh5.execute-api.us-west-2.amazonaws.com/test/data').read()
    
        print content
    
            return 'check console'
    
    if __name__ == '__main__':
        app.run()
    

1 个答案:

答案 0 :(得分:2)

如果你有这样的结构:

>>> response = {"data": [{"login_date": "2014-04-17T19:14:29+08:00", "email": "walter.elwyn@yahoo.com"}, {"login_date": "2014-04-22T09:31:56+04:00", "email": "helyn67@cruickshankmckenzie.com"}]}

然后你所拥有的是一个带有键data

的词典
>>> response['data']
[{'login_date': '2014-04-17T19:14:29+08:00', 'email': 'walter.elwyn@yahoo.com'}, {'login_date': '2014-04-22T09:31:56+04:00', 'email': 'helyn67@cruickshankmckenzie.com'}]

您可以获得列表理解的电子邮件列表:

>>> [user['email'] for user in response['data']]
['walter.elwyn@yahoo.com', 'helyn67@cruickshankmckenzie.com']
  

如何在字典中循环播放独特的电子邮件?

要使该列表唯一,您可以使用集合理解:

>>> {user['email'] for user in response['data']} 
set(['helyn67@cruickshankmckenzie.com', 'walter.elwyn@yahoo.com'])
  

如何通过电子邮件在内容词典中访问特定点

如果您要过滤给定的电子邮件,可以使用filter()

>>> filter(lambda user: user['email'] == 'walter.elwyn@yahoo.com', response['data'])
[{'login_date': '2014-04-17T19:14:29+08:00', 'email': 'walter.elwyn@yahoo.com'}]
  

如果我在我的情况下做内容['数据],我会收到内部服务器错误

那是因为要做content['data']content需要是一个类似dict的对象。让我们使用requests lib来做你想做的事:

>>> import requests
>>> content = requests.get('https://9g9xhayrh5.execute-api.us-west-2.amazonaws.com/test/data')
>>> response = content.json() # reads the data as JSON, into a dict-like object
>>> response.keys()
[u'data']

现在您可以使用response['data']