For the dictionaries in a list, I need to extract and merge them in a single dictionary without overwriting the existing key values.
For example, I have:
mylist = [{'b': 3}, {'b': 9, 'A': 8, 'Z': 2, 'V': 1}]
The result should be:
{'b': 3, 'A': 8, 'Z': 2, 'V': 1}
Below is my code:
def concatenate_dict(dict_list: list) -> dict:
final_dict = {}
for d in dict_list:
for k, v in d.items():
if k not in final_dict:
final_dict |= (k, v)
return final_dict
mylist = [{'b': 7}, {'b': 10, 'A': 8, 'Z': 2, 'V': 1}]
print(concatenate_dict(mylist))
I do not understand why the "not in" keyword would not skip the existing 'b': 10 item and leave 'b': 7 alone and continue to 'A': 8