Update a python dictionary w/ lists

Viewed 106

I'm struggling to update a dictionary of lists using loops.

weather_dict = \
{
"texas": [],
"colorado": = [],
"virginia": = [],
"illinois": = [],
"california": = []
}

arbitrary_weather = [10, 20, 30, 40, 50]

My goal is to have the values of arbitrary_weather pushed into lists within the dictionary using loops. The correlation map is sequential, arbitrary_weather[0] --> texas[], arbitrary_weather[1] --> colorado[], etc. With every iteration of the code, arbitrary_weather is going to change, but the dictionary will continue to append its lists in the same sequential order.

I'm relatively new to python, but working on a graduate project that is going to accumulate a lot of data over time. Eventually, the lists of data within the dictionary will be analyzed using python panda. I have never used panda, so if possible, it would be tremendously helpful to learn best practices for building dictionaries used in data analytics.

Thank you!

2 Answers

If you can make sure the the number of keys in dictionary always equal the len of the list then you can loop through the dictionary and add one at a time

weather_dict = {
    "texas" : [],
    "colorado" : [],
    "virginia" : [],
    "illinois" : [],
    "california" : []
}

arbitrary_weather = [10, 20, 30, 40, 50]
i = 0
for k in weather_dict: 
   weather_dict[k].append(arbitrary_weather[i])
   i += 1

print(weather_dict)

EDIT:

Note that python 3.6 and below iterate through dict is not ordered, if you using python 3.6 and below I suggest using the answer made by Mad Physicist of turning keys into a list so it's ordered

Keep in mind that until python 3.6, dictionaries were not ordered. In fact, you're only using your initial dict as a repository for key names, so I'd recommend storing it as a sequence of key names, not a dictionary with empty values:

states = ['Texas', 'Colorado', 'Illinois', 'California']

You can turn the initial measurements into a dictionary using a comprehension, and append to the lists after that:

weather_dict = {state: [value] for state, value in zip(states, arbitrary_weather)}

You can do that even if you keep the original dictionary as a dictionary, since it is iterable over the keys.

Related