应按特定值过滤的字典列表

时间:2013-03-08 19:54:34

标签: python list dictionary

我有一个dicts列表,并希望只有基于某些键的唯一值。

让我说我有

data = [{name: "John", age: "20", occupation: "Python pro"}, \
        {name: "Jack", age: "80", occupation: "Olympic Athlete"}, \
        {name: "John", age: "20", occupation: "Student"}]

我想基于键'name'和'age'来减少它,使它看起来像

[{name: "John", age: "20", occupation: "Python pro"}, \
 {name: "Jack", age: "80", occupation: "Olympic Athlete"}]

我尝试了以下但没有意识到每次基本上都会添加所有内容的明显问题。

    all_drives =  drivesInBuilder("object") + drivesInBuilder("account") + drivesInBuilder("container")
    reduced_list = [(x["ip address"], x["name"]) for x in all_drives]
    unique_list = list(set(reduced_list))
    unique_drives = [x for x in all_drives if (x["ip address"], x["name"]) in unique_list]
    print(unique_drives)

1 个答案:

答案 0 :(得分:5)

data = [{"name": "John", "age": "20", "occupation": "Python pro"}, \
        {"name": "Jack", "age": "80", "occupation": "Olympic Athlete"}, \
        {"name": "John", "age": "20", "occupation": "Student"}]

new_data = []
names_ages = set([])
for d in data:
    name_age = (d["name"], d["age"])
    if name_age not in names_ages:
        new_data.append(d)
    names_ages.add(name_age)

print new_data
# [{'age': '20', 'name': 'John', 'occupation': 'Python pro'},
#  {'age': '80', 'name': 'Jack', 'occupation': 'Olympic Athlete'}]