2015-12-24 39 views
0

我有這樣一個清單:蟒蛇過濾不同的字典鍵值列表

lis = [{"class":"math","teacher":"Joe"}, {"class": "english","teacher":"Marry"}, 
    {"class": "history","teacher":"Anne"},{"class": "history","teacher":"Bob"} 
    {"class": "math","teacher":"Cathy"}] 

而且我想找到DISTICT class(多少列表中的類):

['math','english','history'] 

哪有我這麼做?

回答

2
from collections import OrderedDict 
from operator import itemgetter 

print(list(OrderedDict.fromkeys(map(itemgetter("class"),lis)))) 
['math', 'english', 'history'] 
+1

謝謝。你的解決方案非常快。 – user2492364

+0

沒有問題,不客氣 –

1

您可以使用set理解(因爲你使用Python> = 2.7.6),如果順序並不重要:

distinct_class = {element['class'] for element in lis} 
print list(distinct_class) 
>> ['history', 'math', 'english'] 
+0

但是,如果爲了事項?.. – alecxe

+0

嗯,我認爲這不是因爲OP不說,它確實:)我將編輯我的答案,以反映這種方式沒有任何意義訂購。 – DeepSpace

0

您可以使用一組的理解,從你的清單建立一套,提取class屬性各dict的:

>>> {x['class'] for x in lis} 
{'history', 'english', 'math'} 

您可以這套轉換到一個列表,如果需要的話,使用list()

如果你想刪除重複時保留順序,然後看this question

1

您可以使用一個for循環遍歷項目,並把它們添加到列表中,如果它是一類新類型。

distinct_classes = [] 

for dist in lis: 
    if dist['class'] not in distinct_classes: 
     distinct_classes.append(dist['class']) 

print distinct_classes