[英]Conditional for to get keys and single values from dictionary of lists
我有一些代碼可以從字典中獲取鍵,以及從包含gallery
的列表中獲取所有值。 該列表已分配給密鑰。
我的代碼:
photos_dict = {}
for key, list in sets_dict.items():
for item in (item for item in list if 'gallery' in item):
photos_dict[key] = item
print(photos_dict)
還有我的字典( sets_dict
):
{
'A':[
'http://example.com/gallery
'http://example.com/video
],
'B':[
'http://example.com/gallery
],
'C':[
'http://example.com/gallery
],
'A':[
'http://example.com/gallery
'http://example.com/video
],
'D':[
'http://example.com/video
'http://example.com/gallery
],
'E':[
'http://example.com/gallery
'http://example.com/video
],
'F':[
'http://example.com/gallery
],
'G':[
'http://example.com/gallery
],
'H':[
'http://example.com/gallery
'http://example.com/video
],
'I':[
'http://example.com/gallery
],
'J':[
'http://example.com/gallery
],
'K':[
'http://example.com/gallery
'http://example.com/video
],
'L':[
'http://example.com/gallery
],
'M':[
'http://example.com/gallery
'http://example.com/video
],
'N':[
'http://example.com/gallery
]
}
有什么辦法可以寫得更短嗎? 我想在第一個for語句中使用if 'gallery in item'
作為條件。
您可以使用dict理解將其編寫為:
{key: link for key, links in photos_dict.items() for link in links if 'gallery' in link}
將此保存在photos_dict
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.