2012-11-14 113 views
0

我有一個(l)的字典列表(l){"id": id, "class": class, "parameter": parameter}。我不得不這樣做,在python中搜索字典的列表

for each value of class: 
    parameter = getParameter(class) //we can get different parameter for same class 
    if {"class":class, "parameter":parameter} not in l: 
     increment id and do l.append({"id": id, "class": class, "parameter": parameter}) 

這裏字典的列表中有3個按鍵,其中,因爲我有在名單與2個鍵進行搜索。我如何驗證'如果'條件?

+1

'id'和'class'是保留字。不要將它們用於變量名稱。 – eumiro

+0

謝謝,我只用這些詞語來表示。實際的代碼是免費的保留字 – Netro

回答

5

如果我理解正確,您的問題是決定是否已經有給定值爲classparameter的條目?你將不得不編寫搜索列表中你的表情,像這樣的:如果發現了一個條目

def search_list(thedict, thelist): 
    return any(x["class"] == thedict["class"] 
       and x["parameter"] == thedict["parameter"] 
       for x in thelist) 

該函數返回true。這樣稱呼它:

if not search_list({"class": class, "parameter": parameter}, l): 
    #the item was not found - do stuff 
+0

'任何'都是救星。這對我來說是新的。 – Netro

0
if {"class":class, "parameter":parameter} not in [{'class':d['class'], 'parameter':d['parameter']} for d in l]: 

您可能不想在每次檢查條件時計算列表,在循環外執行此操作。

+0

使用列表理解似乎是浪費,當你可以用發電機懶洋洋地評估這個。當列表發生變化(找不到的值會被追加),你不能計算一次...... – l4mpi

3
if not any(d['attr1'] == val1 and d['attr2'] == val2 for d in l): 

測試是否存在未在列表lattr1等於val1attr2等於val2字典d

優點是隻要找到匹配就停止迭代。

0

我想用一組對比,可以擺脫那:

>>> d1 = {"id": 1, "class": 3, "parameter": 4} 
>>> d2 = {"id": 1, "class": 3} 
>>> set(d2.items()) < set(d1.items()) 
True 
>>>