[英]grouping a dictionary inside a list in python
我剛剛一直在學習 python 並且我在做一些練習時遇到了麻煩。 我有一個包含字典的列表:
dictionary_title=[
{'Color': 'Green', 'ids': 878},
{'Color': 'Pink', 'ids': 16},
{'Color': 'Orange', 'ids': 28},
{'Color': 'Yellow', 'ids': 9648},
{'Color': 'Red', 'ids': 878},
{'Color': 'Brown', 'ids': 12},
{'Color': 'Black', 'ids': 28},
{'Color': 'White', 'ids': 14},
{'Color': 'Blue', 'ids': 28},
{'Color': 'Light Blue', 'ids': 10751},
{'Color': 'Magenta', 'ids': 28},
{'Color': 'Gray', 'ids': 28}]
現在如果我想按 id 分組,例如:
{878:['Green','Red'], 16:['Pink'], 28:['Orange','Black','Blue','Magenta','Gray'] and so on...}
現在這是我的代碼:
dictionary={}
genres=[878,16,28,9648,12,14,10751]
for color in nodes:
for index in range(0,len(genres)):
if genres[index] == color["ids"]:
dictionary.setdefault(genres[index],[])
dictionary[genres[index]].append(color["color"])
print(dictionary)
但我的 output 是:
{878:['Green','Pink','Orange','Yellow','Red','Brown','Black','White','Blue','Light Blue','Magenta','Gray']}
我能怎么做?
您不需要嵌套循環。 只需遍歷列表即可。 如果您只想處理genres
中的 id,請為此添加一個測試,而不是另一個循環(如果genres
很長,請將其轉換為一個set
以獲得更好的性能)。
for d in dictionary_title:
if d['ids'] in genres:
dictionary.setdefault(d['ids'], []).append(d['Color'])
print(dictionary)
或者,使用defaultdict
:
from collections import defaultdict
dictionary = defaultdict(list)
for d in dictionary_title:
dictionary[d['ids']].append(d['Color'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.