使用带有If / Else条件的字典理解从API响应中选择键/值对

问题描述

我已经编译了一个名为“ user_responses”的API响应列表。这是列表中响应的示例:

{
    "ok": true,"members": [
        {
            "id": "W012A3CDE","team_id": "T012AB3C4","name": "spengler","deleted": false,"color": "9f69e7","real_name": "spengler","tz": "America/Los_Angeles","tz_label": "Pacific Daylight Time","tz_offset": -25200,"profile": {
                "avatar_hash": "ge3b51ca72de","status_text": "Print is dead","status_emoji": ":books:","real_name": "Egon Spengler","display_name": "spengler","real_name_normalized": "Egon Spengler","display_name_normalized": "spengler","email": "spengler@ghostbusters.example.com","image_24": "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg","image_32": "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg","image_48": "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg","image_72": "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg","image_192": "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg","image_512": "https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg","team": "T012AB3C4"
            },"is_admin": true,"is_owner": false,"is_primary_owner": false,"is_restricted": false,"is_ultra_restricted": false,"is_bot": false,"updated": 1502138686,"is_app_user": false,"has_2fa": false
        },{
            "id": "W07QCRPA4","team_id": "T0G9PQBBK","name": "glinda","real_name": "Glinda Southgood","profile": {
                "avatar_hash": "8fbdd10b41c6","image_24": "https://a.slack-edge.com...png","image_32": "https://a.slack-edge.com...png","image_48": "https://a.slack-edge.com...png","image_72": "https://a.slack-edge.com...png","image_192": "https://a.slack-edge.com...png","image_512": "https://a.slack-edge.com...png","image_1024": "https://a.slack-edge.com...png","image_original": "https://a.slack-edge.com...png","first_name": "Glinda","last_name": "Southgood","title": "Glinda the Good","phone": "","skype": "","real_name_normalized": "Glinda Southgood","display_name": "Glinda the Fairly Good","display_name_normalized": "Glinda the Fairly Good","email": "glenda@south.oz.coven"
            },"updated": 1480527098,"has_2fa": false
        }
    ],"cache_ts": 1498777272,"response_Metadata": {
        "next_cursor": "dXNlcjpVMEc5V0ZYTlo="
    }
}

我想建立一个包含以下内容的字典

1。一个密钥,即用户的real_name。如果没有用户的真实姓名,那么我想为该用户使用display_name。

为此,我尝试在字典理解中使用三元表达式来处理if / else条件:

{(sub_dict['profile']['real_name'] if 'real_name' in sub_dict['profile] 
  else sub_dict['profile']['display_name']):value
  for response in user_responses
  for sub_dict in response.get('members')}

这似乎只是认情况下,为每个用户使用display_name,这不是我想要的。

2。该值是每个用户的所有图像的列表。

为此,我想我可以编写一个列表理解,其中包括以“ image”开头的所有键的值。

{(key:[sub_dict['profile'][k] for k in sub_dict['profile'] if k.startswith('image')]
  for response in user_responses
  for sub_dict in response.get('members')}

是否有更好的方法可以做到这一点?预先感谢您的帮助。

解决方法

一种将for循环简化为理解的好方法是,首先使用常规的for循环可视化该过程:

newLst = []
for member in var["members"]:
    d = {"images": []}
    for k,v in member["profile"].items():
        if k.startswith("image"):
            d["images"].append(v)

    d["name"] = member["profile"].get("real_name")
    if not d["name"]:
        member["profile"].get("display_name")
    newLst.append(d)

现在,我个人将使用上面的for循环。但是,您的问题是如何使用理解力解决该问题,所以这是我的说法:

newLst = [{"images": [v for k,v in member["profile"].items() if k.startswith("image")],"name": member["profile"].get("real_name",member["profile"].get("display_name"))} for member in var["members"]]

两者的最大区别在于,第一个非常容易调试,或者至少遵循了逻辑。虽然第二个要真正跟随起来要困难得多。

两者的结果:

[{'images': ['https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg','https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg','https://.../avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg'],'name': 'Egon Spengler'},{'images': ['https://a.slack-edge.com...png','https://a.slack-edge.com...png','https://a.slack-edge.com...png'],'name': 'Glinda Southgood'}]