[英]python : how to check list in dict
我想檢查type
中的每個項目是否在dict typeurl
。 如果URL圖像在詞典中,我將保存其名稱。
以下是我的代碼,但是我不確定這是否是執行此操作的好方法。
如果有更好的寫方法,請指導我:
type = ['https://test/1.jpeg','https://test/3.jpeg']
typeurl = {
u'Max' : 'https://test/1.jpeg',
u'MIX' : 'https://test/2.jpeg',
u'Special': 'https://test/dd/1.jpeg',
u'Medium' : 'https://test/3.jpeg',
}
en = []
for t in type:
for i in typeurl:
if t in typeurl[i]:
print i
en.append(i)
print " | ".join(en) #output Max | Medium
您可以通過過濾和生成器表達式來完成此操作
>>> " | ".join(item for item in typeurl if typeurl[item] in types)
Max | Medium
在這里,我們遍歷typeurl
的鍵,並且如果與鍵對應的值在types
,則將其包括在生成器表達式的結果中。 最后,我們將所有元素與|
。
注意:由於我們按類型進行查找,因此最好將其設置為一個集合,以使查找速度更快。
types = {'https://test/1.jpeg', 'https://test/3.jpeg'}
注意:名稱type
有一個內置函數。 因此,使用相同的名稱命名變量將使內置函數無效。 這就是為什么我使用名稱types
。
這更緊湊。
print ' | '.join([key for key, val in typeurl.iteritems() if val in type])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.