Home > database >  Change value of dictionary if it is in another dictionary
Change value of dictionary if it is in another dictionary

Time:11-22

I have two lists of generated dictionaries. One is like a template structured like:

list_of_dicts_template = [{'year': 0, 'week': 38, 'count_tickets': 0}, {'year': 0, 'week': 39, 'count_tickets': 0}]...

And another is a dictionary with values that we know: known_values_list = [{'year': 2022, 'week': 39, 'tickets': 47}, {'year': 2022, 'week': 40, 'tickets': 3}]... My problem is, I want to mix them in one list of dictionaries. Where if value of key 'week' is in list of dicts known_values_list, it will replace whole dict in list_of_dicts_template.

So the expected list of dicts would look like: final_list = [{'year': 0, 'week': 38, 'count_tickets': 0}, {'year': 2022, 'week': 39, 'count_tickets': 47}, {'year': 2022, 'week': 40, 'tickets': 3}]... `

I actually don't know how to approach this problem. If I had only dicts without array, I would do something like:

for sub in dicts_template:
    if(sub in known_values):
        dicts_template[sub] = known_values[sub]

But if it's in arrays, I'm completely lost.

CodePudding user response:

You could use the following code:

for i,d1 in enumerate(list_of_dicts_template):
    for j, known_value_d in enumerate(known_values_list):
        if known_value_d['week'] == d1['week']:
            list_of_dicts_template[i] = known_value_d
            del known_values_list[j]

To add only delete the element in the known_values_list, if there shouldn't be any duplicate weeks in the list_of_dicts_template.

  • Related