Initialize List to a Variable in a Dictionary Inside a Loop

Initialize List to a variable in a Dictionary inside a loop

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'])

Adding item to Dictionary within loop

In your current code, what Dictionary.update() does is that it updates (update means the value is overwritten from the value for same key in passed in dictionary) the keys in current dictionary with the values from the dictionary passed in as the parameter to it (adding any new key:value pairs if existing) . A single flat dictionary does not satisfy your requirement , you either need a list of dictionaries or a dictionary with nested dictionaries.

If you want a list of dictionaries (where each element in the list would be a diciotnary of a entry) then you can make case_list as a list and then append case to it (instead of update) .

Example -

case_list = []
for entry in entries_list:
case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
case_list.append(case)

Or you can also have a dictionary of dictionaries with the key of each element in the dictionary being entry1 or entry2 , etc and the value being the corresponding dictionary for that entry.

case_list = {}
for entry in entries_list:
case = {'key1': value, 'key2': value, 'key3':value }
case_list[entryname] = case #you will need to come up with the logic to get the entryname.

Initialization of a list of dictionaries

The important part is this line:

cell = {"name": "","age" : 0, "education" : "","height" : 0}

here you create a dictionary and save a reference to it under cell

If you do this before the loop (like in your second example) you have only created one dictionary and appended it to the list three times. So if you change anything inside of any dictionary, your changes will show up at all indices of the list (since they all point to the same dictionary)

However, if you run the line inside of your loop you actually create three different dictionaries, which is essentially what you want here. This is why your first example works and your second one doesn't.

Appending a dictionary to a list in a loop

You need to append a copy, otherwise you are just adding references to the same dictionary over and over again:

yourlist.append(yourdict.copy())

I used yourdict and yourlist instead of dict and list; you don't want to mask the built-in types.

Multiple dictionary list of values assignment with a single for loop for multiple keys

You can make use of defaultdict. There is no need to split the line each time, and to make it more readable you can use a lambda to extract the fields for each item.

from collections import defaultdict

res = defaultdict(list)

with open('/home/user/test', 'r') as f:
for line in f:
items = line.split()
extract = lambda x: x.split(':')[1]

res['p_avg'].append(extract(items[5]))
res['p_y'].append(extract(items[6]))
res['m_avg'].append(extract(items[1]))
res['m_y'].append(extract(items[2]))

Appending to list in Python dictionary

list.append returns None, since it is an in-place operation and you are assigning it back to dates_dict[key]. So, the next time when you do dates_dict.get(key, []).append you are actually doing None.append. That is why it is failing. Instead, you can simply do

dates_dict.setdefault(key, []).append(date)

But, we have collections.defaultdict for this purpose only. You can do something like this

from collections import defaultdict
dates_dict = defaultdict(list)
for key, date in cur:
dates_dict[key].append(date)

This will create a new list object, if the key is not found in the dictionary.

Note: Since the defaultdict will create a new list if the key is not found in the dictionary, this will have unintented side-effects. For example, if you simply want to retrieve a value for the key, which is not there, it will create a new list and return it.

Build Dictionary in Python Loop - List and Dictionary Comprehensions

The short form is as follows (called dict comprehension, as analogy to the list comprehension, set comprehension etc.):

x = { row.SITE_NAME : row.LOOKUP_TABLE for row in cursor }

so in general given some _container with some kind of elements and a function _value which for a given element returns the value that you want to add to this key in the dictionary:

{ _key : _value(_key) for _key in _container }

How to loop through a dictionary and assign values to a variable based on keys?

you're close! look here

for params in all_params:
m = Prophet(
changepoint_prior_scale = all_params['changepoint_prior_scale'],
changepoint_range = all_params['changepoint_range'],
seasonality_mode = 'multiplicative',...

notice that you made params but are still using all_params for access!
change it like this:

for params in all_params:
m = Prophet(
changepoint_prior_scale = params['changepoint_prior_scale'],
changepoint_range = params['changepoint_range'],
seasonality_mode = 'multiplicative',...

How to create list inside for loop?

For this task I would choose a different data structure dict()

This will let You map the keys to respective lists such as:

my_dictionary = {}
for i in range(5):
my_dictionary[f"list_{i}"] = [] # This might be also my_dictionary["list_"+str(i)]

Please note that I have used empty list as key -> value mapping.

This in turn will produce a following dictionary:

{"list_0": [], "list_1": [], "list_2": [], "list_3":[], "list_4":[]}


Related Topics



Leave a reply



Submit