如何解决在具有不同键顺序的不同列表中搜索键,值
我正在使用tweepy来检索json中的链接。我提取了一个包含字典的列表。它们大多数都具有相同的模式(键和值的顺序相同),如下所示
[{'bitrate': 2176000,'content_type': 'video/mp4','url': 'https://A_LINK'},{'bitrate': 632000,'url': 'https://B_LINK'},{'content_type': 'application/x-mpegURL','url': 'https://C_LINK'},{'bitrate': 832000,'url': 'https://D_LINK'}]
上述模式有两个特点:
1。{'bitrate': 2176000,'url': 'https://A_LINK'}
位于{'content_type': 'application/x-mpegURL','url': 'https://C_LINK'}
的前部
2。{'content_type': 'application/x-mpegURL','url': 'https://C_LINK'}
正在丢失密钥比特率
我想找到比特率为 2176000 的网址(示例为 https:// A_LINK ),以下代码可以正常工作与上述模式有关,我可以找到 https:// A_LINK
link = next((item for item in x if item["bitrate"] == 2176000),None)
print(link["url"])
但是,由于{'content_type': 'application/x-mpegURL','url': 'https://C_LINK'}
正在丢失密钥比特率
它将在以下模式中导致错误。
[{'bitrate': 632000,{'bitrate': 2176000,'url': 'https://D_LINK'}]
对于上述模式,
{'bitrate': 2176000,'url': 'https://D_LINK'}
位于'content_type': 'application/x-mpegURL'
之后
每当我收到这样的图案时,我都会收到错误
KeyError: 'bitrate'
在{'content_type': 'application/x-mpegURL','url': 'https://C_LINK'}
之后我无法获得 https:// D_LINK
因此,我问,当我收到第二个列表模式时,
有没有一种方法可以所谓的“绕过” {'content_type': 'application/x-mpegURL','url': 'https://C_LINK'}
这样我就可以得到 https:// D_LINK ,它的比特率是 2176000 ?
谢谢。
解决方法
这是您要找的吗?
l = [
{'bitrate': 632000,'content_type': 'video/mp4','url': 'https://A_LINK'},{'bitrate': 832000,'url': 'https://B_LINK'},{'content_type': 'application/x-mpegURL','url': 'https://C_LINK'},{'bitrate': 2176000,'url': 'https://D_LINK'},]
''.join([d["url"] for d in l if "bitrate" in d.keys() and d['bitrate'] == 2176000])
输出:
'https://D_LINK'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。