Python 3.x 在具有不同键顺序的不同列表中搜索键、值
我使用tweepy检索json中的链接。我提取了一个包含字典的列表。它们中的大多数具有相同的模式(键和值的顺序相同),如下所示Python 3.x 在具有不同键顺序的不同列表中搜索键、值,python-3.x,list,dictionary,tweepy,Python 3.x,List,Dictionary,Tweepy,我使用tweepy检索json中的链接。我提取了一个包含字典的列表。它们中的大多数具有相同的模式(键和值的顺序相同),如下所示 [{'bitrate': 2176000, 'content_type': 'video/mp4', 'url': 'https://A_LINK'}, {'bitrate': 632000, 'content_type': 'video/mp4', 'url': 'https://B_LINK'}, {'content_type': 'application/x-m
[{'bitrate': 2176000, 'content_type': 'video/mp4', 'url': 'https://A_LINK'},
{'bitrate': 632000, 'content_type': 'video/mp4', 'url': 'https://B_LINK'},
{'content_type': 'application/x-mpegURL', 'url': 'https://C_LINK'},
{'bitrate': 832000, 'content_type': 'video/mp4', 'url': 'https://D_LINK'}]
上述模式有两个特点:
1.{'bitrate':2176000,'content_type':'video/mp4','url':'https://A_LINK“}
位于{'content\u type':'application/x-mpegURL','url':'https://C_LINK“}
2.{'content_type':'application/x-mpegur','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-mpegur','url':'https://C_LINK“}
缺少键比特率
它将导致以下模式中的错误
[{'bitrate': 632000, 'content_type': 'video/mp4', 'url': 'https://A_LINK'},
{'bitrate': 832000, 'content_type': 'video/mp4', 'url': 'https://B_LINK'},
{'content_type': 'application/x-mpegURL', 'url': 'https://C_LINK'},
{'bitrate': 2176000, 'content_type': 'video/mp4', 'url': 'https://D_LINK'}]
对于上述模式
{'bitrate':2176000,'content_type':'video/mp4','url':'https://D_LINK“}
位于'content\u type':'application/x-mpegURL'
每当我收到这样的模式,我就会收到错误
KeyError:“比特率”
而且我不能得到https://D_LINK在{'content\u type':'application/x-mpegURL','url':'https://C_LINK“}
因此我在问,当我收到第二个列表模式时
有没有一种方法可以“绕过”{'content_type':'application/x-mpegur','url':'https://C_LINK“}
这样我就可以得到https://D_LINK最后哪个比特率2176000
谢谢。这就是你要找的吗
l = [
{'bitrate': 632000, 'content_type': 'video/mp4', 'url': 'https://A_LINK'},
{'bitrate': 832000, 'content_type': 'video/mp4', 'url': 'https://B_LINK'},
{'content_type': 'application/x-mpegURL', 'url': 'https://C_LINK'},
{'bitrate': 2176000, 'content_type': 'video/mp4', 'url': 'https://D_LINK'},
]
''.join([d["url"] for d in l if "bitrate" in d.keys() and d['bitrate'] == 2176000])
输出:
'https://D_LINK'
dict.get(key\u name)
可能适合您。如果密钥不存在,它将返回None
,并且不会引发KeyError
。在您的情况下,link=next((如果item.get(“比特率”)==2176000,则x中的项对应项),None)
非常感谢,它很有效。谢谢,这几乎就是我想要的。然而,在列表中的输出,有没有一种方法可以在代码中将其作为字符串输出?