【问题标题】:How to add items from a list of dictionarys to another list using IF conditions如何使用 IF 条件将字典列表中的项目添加到另一个列表
【发布时间】:2021-12-30 19:08:22
【问题描述】:

我想通过从另一个字典列表中获取某些键和值来构建我自己的字典列表。我还需要检查某些键是否存在以过滤它们,如果它们中的一些存在,则只提取一些部分。

这里是字典的原始列表:

messages_raw_json = [
        #item_dict_1
        {
            "_id": "1",
            "msg": "Hi friends",
            "ts": "2021-11-20T06:14:42.374Z",
            "u": {
                "_id": "user1",
                "username": "verz",
                "name": "vrodriguez"
            },
            "_updatedAt": "2021-11-20T06:14:42.586Z",
            "urls": []
        },

         #item_dict_2
        {
            "_id": "2",
            "ts": "2021-11-18T16:52:37.620Z",
            "msg": "",
            "u": {
                "_id": "user2",
                "username": "2cats",
                "name": "Two Cats"
            },
            "_updatedAt": "2021-11-18T16:54:34.285Z",
            "urls": [],
            "t": "msg_removed"
        },

         #item_dict_3
        {
            "_id": "3",
            "ts": "2021-11-18T16:52:37.620Z",
            "msg": "",
            "attachments": [
                {
                    "ts": "1970-01-01T00:00:00.000Z",
                    "title": "image.png",
                    "image_url": "/file-upload/SpacZwkFjWRzdW8eh/image.png",
                    "description": "testing uploading image",
                }
            ],
            "u": {
                "_id": "user3",
                "username": "blas3",
                "name": "blasito"
            },
            "_updatedAt": "2021-11-18T16:54:34.267Z",
            "urls": []
        },

         #item_dict_4
        {
            "_id": "4",
            "t": "user_join",
            "ts": "2021-11-17T20:05:48.043Z",
            "msg": "testing",
            "u": {
                "_id": "user4",
                "username": "micheal11",
                "name": "george"
            },
            "_updatedAt": "2021-11-17T20:05:48.065Z"
        },

         #item_dict_5
        {
            "_id": "5",

            "msg": "Another message here",
            "ts": "2021-11-14T19:59:11.428Z",
            "u": {
                "_id": "user5",
                "username": "Mason78",
                "name": "stuart"
            },
            "_updatedAt": "2021-11-14T19:59:11.770Z",
            "urls": [
                {
                    "url": "https://wa.me/c/12345",
                    "headers": {
                        "contentType": "text/html; charset=\"utf-8\""
                    },
                }
            ]
        }
    ]

我的第一个条件是检查 item dict 是否包含名为 't' 的键,在这种情况下,我想跳过它。这个 IF 语句正确处理了这种情况:

if 't' in message.keys():
   continue

然后我想从键 'urls' 中获取 url,如果它不为空的话。 'attachments' 也是一样,我只想从'title'、'image_url' 和'description' 中获取值,但这是我苦苦挣扎的地方。

这是我写的不工作的代码。我理解为什么(并非所有项目都有我要检索的密钥),但老实说,由于我是 Python 的初学者,我不知道如何编写其他条件以使其工作。提前感谢您的帮助。

messages = []
for message in messages_raw_json:
    if 't' in message.keys():
        continue
    data = {
        'time': message['ts'],
        'name': message['u']['name'],
        'username': message['u']['username'],
        'msg': message['msg'],
        'url': message['urls'][0]['url'],
        'attach_file': message['attachments']['title'],
        'attach_file': message['attachments']['image_url'],
        'attach_file': message['attachments']['description']
        }
    messages.append(data)

print(messages)

【问题讨论】:

    标签: python list dictionary if-statement


    【解决方案1】:

    据我所知,您正在尝试获取所有数据,但键为“t”的数据除外。

    要获取一条您不确定是否存在的数据,只需使用:

    message.get(key, exceptionvalue)
    # Where 'exception value' is simply what it returns if the key does not exist
    

    例如:

    data  = {
            "url" : message.get("url", None)
            }
    

    请注意,尝试获取每一个值并不是有效的。如果它是一维字典,您可以创建一个键(和异常值)列表并进行迭代,但在这种情况下这并不合理。

    【讨论】:

    • 谢谢拉里的提示,确实,就像它检查并添加键的值是否存在,如果不存在,只需添加键和值无。在我的示例中有些棘手,因为我不想从“附件”或“网址”中获取全部值,而只是从附件中获取“标题”或“描述”或从“网址”中获取“网址” '
    • ... 你可以在其中使用.get("attachments",{}).get("title",None) 或类似的东西
    • 感谢您回到这个问题。遗憾的是,它并没有按照您的建议工作:/ 我尝试了一些变体但没有运气。
    • 没问题 - 希望它有助于让您的程序进入写入轨道。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2013-03-25
    • 2021-08-18
    相关资源
    最近更新 更多