【发布时间】: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