Fmrubio
Fmrubio

Reputation: 365

Initialize List to a variable in a Dictionary inside a loop

I have been working for a while in Python and I have solved this issue using "try" and "except", but I was wondering if there is another method 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 content:

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

My way to implement the example_dictionary was:

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.

Upvotes: 27

Views: 19651

Answers (3)

Darth Moon Moon
Darth Moon Moon

Reputation: 1

There seems to be a way to do this without using collections.defaultdict() or dict.setdefault().


>>> root_vals = [{"name":"red","value":2},{"name":"red","value":3},{"name":"red","value":4}]
>>> hashmap = {}
>>> for item in root_vals:
...     k, v = item["name"], item["value"]
...     hashmap[k] = hashmap.get(k, []) + [v]
... 
>>> hashmap
{'red': [2, 3, 4]}

Upvotes: 0

ssm
ssm

Reputation: 5373

List and dictionary comprehensions can help here ...

Given

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 extract 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, its just a matter of dictionary comprehension ...

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]}

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122092

Your code is not appending elements to the lists; you are instead replacing the list with single elements. To access values in your existing dictionaries, you must use indexing, not attribute lookups (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 dict subclass that uses the __missing__ hook on dict to auto-materialize values if the key doesn't yet exist in the mapping.

or use dict.setdefault():

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

Upvotes: 51

Related Questions