![](/img/trans.png)
[英]How to extract values from list of dictionary that match the keys in another list
[英]How to match values from a dictionary to a list of keys
我有一个称为keys的列表:
[
'id','edge_media_to_caption','shortcode','edge_media_to_comment',
'taken_at_timestamp','display_url','edge_liked_by','owner'
]
另一个带有嵌套字典的列表称为posts ,看起来像这样:
"posts": [
{
"node": {
"comments_disabled": "false",
"__typename": "GraphImage",
"id": "2018763372224677501",
"edge_media_to_caption": {
"edges": [
{
"node": {
"text": "Advertisement | Soon it\u2019s festival season and I seriously can\u2019t wait to join Roskilde Festival once again! Good friends and a solid bag like this beautiful bumbag from @markberg_access is all you need (it has more space than you might think) \ud83c\udf7b\ud83d\ude4c\ud83c\udffd #markberg #we\u2764\ufe0felinor"
}
}
]
},
"shortcode": "BwEFpdXBYZ9",
"edge_media_to_comment": {
"count": 2
},
"taken_at_timestamp": 1554875369,
"dimensions": {
"height": 1350,
"width": 1080
},
"display_url": "https://scontent-arn2-2.cdninstagram.com/vp/cefd572491a0c6c9f0822987f2107b88/5D41FE6F/t51.2885-15/e35/54731678_835552086798320_4599970429294248448_n.jpg?_nc_ht=scontent-arn2-2.cdninstagram.com",
"edge_liked_by": {
"count": 286
},
"edge_media_preview_like": {
"count": 286
},
"owner": {
"id": "1638100776"
}
}
如何遍历posts
并与keys
匹配? (帖子要长得多,但出于说明目的,我仅添加了一个节点)。
先感谢您!
res = []
for post in posts:
a = {}
for key in keys:
if key in post['node'].keys():
a[key] = post['node'][key]
res.append(a)
结果:
res = [
{
"id": "2018763372224677501",
"edge_media_to_caption": {
"edges": [
{
"node": {
"text": "Advertisement | Soon it\u2019s festival season and I seriously can\u2019t wait to join Roskilde Festival once again! Good friends and a solid bag like this beautiful bumbag from @markberg_access is all you need (it has more space than you might think) \ud83c\udf7b\ud83d\ude4c\ud83c\udffd #markberg #we\u2764\ufe0felinor"
}
}
]
},
"shortcode": "BwEFpdXBYZ9",
"edge_media_to_comment": {
"count": 2
},
"taken_at_timestamp": 1554875369,
"display_url": "https://scontent-arn2-2.cdninstagram.com/vp/cefd572491a0c6c9f0822987f2107b88/5D41FE6F/t51.2885-15/e35/54731678_835552086798320_4599970429294248448_n.jpg?_nc_ht=scontent-arn2-2.cdninstagram.com",
"edge_liked_by": {
"count": 286
},
"owner": {
"id": "1638100776"
}
}
]
但仅适用于"node"
键
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.