SaidAkh SaidAkh - 3 days ago 5
Python Question

Build a list of dictionaries which is resulted from `for` loop with `if` statement, where each dictionary key is the same

I need to build a list of dictionaries which is resulted from

for
loop with
if
statement, where each dictionary key is the same. How can I do it? Thanks in advance

list = []
dict = {}

for item in some_other_list
if item == 0:
dict.update({'the_key_which_is_always_same_word': item.value})
else:
dict.update({'the_key_which_is_always_same_word': item.value})


the result of
list
after
for
loop should look like:

[{'the_key_which_is_always_same_word': 'value_1'},
{'the_key_which_is_always_same_word': 'value_2'},
{'the_key_which_is_always_same_word': 'value_3'}]

Answer

The logic is all there, but I don't think you are adding items to the right object.

dict.update updates the dictionary that you've created. And by "updates", it will join the two dictionaries together. If the key already exists, it will update that key with the given value. If not, it will create a new key with that value. So, you are constantly updating your dict variable, not the list. To add values to the end of a list, you should use append.

list = []

for item in some_other_list
    dict = {}
    if item == 0:
        dict['the_key_which_is_always_same_word'] = item.value
    else:
        dict['the_key_which_is_always_same_word'] = item.value
    list.append(dict)

What this will do is, for each iteration of the loop, create a new dictionary. If item is 0, we will write item.value to a given key. Otherwise, we write it to a different key. I'm assuming that in your actual code, the two keys are different. If they aren't, then this if/else block is pointless.

After this, we append it to the end of the list.

List Comprehension

This could also be done in one line with list comprehension if you want:

[{"the_key_which_is_always_same_word":i} if i == 0 else {"the_key_which_is_always_same_word":i} for i in some_other_list]

If i==0, the first dictionary will be placed in the list, otherwise, the second one will be.

Comments