-1

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

可以说我有

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)
4

1 回答 1

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'}]
于 2013-03-08T20:05:13.493 回答