Initialize a list for a variable in a dictionary inside a loop

I worked for some time in Python and I solved this problem using "try" and "except", but I was wondering if there is another way to solve it.

Basically, I want to create a dictionary like this:

example_dictionary = {"red":[2,3,4],"blue":[6,7,8],"orange":[10,11,12]} 

So, if I have a variable with the following contents:

 root_values = [{"name":"red","value":2},{"name":"red","value":3},{"name":"red","value":4},{"blue":6}...] 

My way to implement example_dictionary:

 example_dictionary = {} for item in root_values: try: example_dictionary[item.name].append(item.value) except: example_dictionary[item.name] =[item.value] 

I hope my question is clear and someone can help me with this.

Thanks.

+6
source share
2 answers

Your code does not add items to lists; instead, you replace the list with individual items. To access values โ€‹โ€‹in existing dictionaries, you must use indexing rather than attribute searching ( item['name'] , not item.name ).

Use collections.defaultdict() :

 from collections import defaultdict example_dictionary = defaultdict(list) for item in root_values: example_dictionary[item['name']].append(item['value']) 

defaultdict is a subclass of dict that uses the __missing__ hook on the dict to automatically create values โ€‹โ€‹if the key does not already exist in the mapping.

or use dict.setdefault() :

 example_dictionary = {} for item in root_values: example_dictionary.setdefault(item['name'], []).append(item['value']) 
+16
source

List and Dictionary functions can help here ...

Considering

 In [72]: root_values Out[72]: [{'name': 'red', 'value': 2}, {'name': 'red', 'value': 3}, {'name': 'red', 'value': 2}, {'name': 'green', 'value': 7}, {'name': 'green', 'value': 8}, {'name': 'green', 'value': 9}, {'name': 'blue', 'value': 4}, {'name': 'blue', 'value': 4}, {'name': 'blue', 'value': 4}] 

A function like item() shown below can retrieve values โ€‹โ€‹with specific names:

 In [75]: def item(x): return [m['value'] for m in root_values if m['name']==x] In [76]: item('red') Out[76]: [2, 3, 2] 

Then it's just a matter of understanding the dictionary ...

 In [77]: {x:item(x) for x in ['red', 'green', 'blue'] } Out[77]: {'blue': [4, 4, 4], 'green': [7, 8, 9], 'red': [2, 3, 2]} 
0
source

All Articles