2017-08-01 135 views
2

我有一個字典列表,其中的字典也包含一個列表。從列表字典中獲取一組唯一值

我想要生成set的各個嵌套列表的值,以便我最終得到一組所有的唯一項目(在這種情況下,愛好)。

我覺得set是完美的,因爲它會自動刪除任何重複的東西,給我留下一整套獨特的愛好。

people = [{'name': 'John', 'age': 47, 'hobbies': ['Python', 'cooking', 'reading']}, 
      {'name': 'Mary', 'age': 16, 'hobbies': ['horses', 'cooking', 'art']}, 
      {'name': 'Bob', 'age': 14, 'hobbies': ['Python', 'piano', 'cooking']}, 
      {'name': 'Sally', 'age': 11, 'hobbies': ['biking', 'cooking']}, 
      {'name': 'Mark', 'age': 54, 'hobbies': ['hiking', 'camping', 'Python', 'chess']}, 
      {'name': 'Alisa', 'age': 52, 'hobbies': ['camping', 'reading']}, 
      {'name': 'Megan', 'age': 21, 'hobbies': ['lizards', 'reading']}, 
      {'name': 'Amanda', 'age': 19, 'hobbies': ['turtles']}, 
      ] 

unique_hobbies = (item for item in people['hobbies'] for hobby in people['hobbies'].items()) 

print(unique_hobbies) 

這會產生一個錯誤:

TypeError: list indices must be integers or slices, not str 

修真是錯的,但我不知道在哪裏。我想遍歷每一個字典,然後迭代每個嵌套列表並將這些項目更新到集合中,這將刪除所有重複項,留下一組所有獨特的興趣愛好。

回答

1

你也可以使用一組-理解:

>>> unique_hobbies = {hobby for persondct in people for hobby in persondct['hobbies']} 
>>> unique_hobbies 
{'horses', 'lizards', 'cooking', 'art', 'biking', 'camping', 'reading', 'piano', 'hiking', 'turtles', 'Python', 'chess'} 

與你的理解的問題是,您要訪問people['hobbies']people是列表,可以只有帶整數或切片的索引列表。爲了使它工作,你需要迭代你的列表,然後訪問每個子項的'hobbies'(就像我在上面的集合理解中做的那樣)。

+0

這回答我的問題,但我有一個後續行動,如果我可以。它有效,但是PyCharm正在拋出一個警告,這是我的理解正在發揮作用以來所沒有的。警告是:預期的'collections.iterable',取而代之的是'Union [str,int,List [str]]'。 – MarkS

+0

不確定這是什麼意思,因爲「嗜好」都是'List [str]'。也許PyCharm將某些東西與其他字典條目混淆起來(對於名字來說名字和'int'是'str')。 – MSeifert

1

我懂了:

unique_hobbies = set() 

for d in people: 
    unique_hobbies.update(d['hobbies']) 

print(unique_hobbies)