I've just been studying python and I'm having trouble doing some exercises. I have a list containing, I think, a dictionary:
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}]
now if i want to group by id, to have for example:
{878:['Green','Red'], 16:['Pink'], 28:['Orange','Black','Blue','Magenta','Gray'] and so on...}
Now this is my code:
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)
but my output is:
{878:['Green','Pink','Orange','Yellow','Red','Brown','Black','White','Blue','Light Blue','Magenta','Gray']}
How can i do?
CodePudding user response:
You don't need nested loops. Just loop over the list. If you only want to process the ids that are in genres
, add a test for that, rather than another loop (if genres
is long, convert it to a set
for better performance).
for d in dictionary_title:
if d['ids'] in genres:
dictionary.setdefault(d['ids'], []).append(d['Color'])
print(dictionary)
CodePudding user response:
Alternatively, use defaultdict
:
from collections import defaultdict
dictionary = defaultdict(list)
for d in dictionary_title:
dictionary[d['ids']].append(d['Color'])