Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize List to a variable in a Dictionary inside a loop

Tags:

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.

like image 340
Fmrubio Avatar asked Apr 01 '14 10:04

Fmrubio


People also ask

Can you append a list to a dictionary?

By using ” + ” operator we can append the lists of each key inside a dictionary in Python.

Can you have a list inside a dictionary in Python?

Note that the restriction with keys in Python dictionary is only immutable data types can be used as keys, which means we cannot use a dictionary of list as a key . But the same can be done very wisely with values in dictionary. Let's see all the different ways we can create a dictionary of Lists.

How do I convert a list to a dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

How do you update a list of values in a dictionary?

Method 1: Using append() function The append function is used to insert a new value in the list of dictionaries, we will use pop() function along with this to eliminate the duplicate data. Syntax: dictionary[row]['key']. append('value')


1 Answers

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'])
like image 168
Martijn Pieters Avatar answered Sep 30 '22 19:09

Martijn Pieters