Home > database >  Efficient way to copy pairs(key ,value) of dictionary in a list of dictionaries, and respect order
Efficient way to copy pairs(key ,value) of dictionary in a list of dictionaries, and respect order

Time:10-13

I want to copy a common dictionary

list_common_dictionary = [{'Gender':'M', 'Age':'25'}]

inside a data list dictionary \

list_data_dictionary = [{'name':'john','id':'1'},
                        {'name':'albert','id':'2'},
                        {'name':'jasper','id':'3'},
                        {'name':'guillaume','id':'4'}]

and get an output like :

output_dictionary = [{'Gender':'M', 'Age':'25','name':'john','id':'1'},
                     {'Gender':'M', 'Age':'25','name':'albert','id':'2'},
                     {'Gender':'M', 'Age':'25','name':'jasper','id':'3'},
                     {'Gender':'M', 'Age':'25','name':'guillaume','id':'4'}]

But respect the order of (fields of the common dictionary must be at the beginning of each output dictionary.
Regarding time cpu consumption, is deepcopy the most efficient way ?

CodePudding user response:

Use:

result = [{**list_common_dictionary[0], **d} for d in list_data_dictionary]
print(result)

Output

[{'Gender': 'M', 'Age': '25', 'name': 'john', 'id': '1'}, {'Gender': 'M', 'Age': '25', 'name': 'albert', 'id': '2'}, {'Gender': 'M', 'Age': '25', 'name': 'jasper', 'id': '3'}, {'Gender': 'M', 'Age': '25', 'name': 'guillaume', 'id': '4'}]

Dictionaries keep insertion order in Python 3.6 so this will guarantee that the keys from the common dictionary are the first ones.

CodePudding user response:

You can use update in-place dictionary like below:

You can read here:

For those coming late to the party, I had put some timing together (Py 3.7), showing that .update() based methods look a bit (~5%) faster when inputs are preserved and noticeably (~30%) faster when just updating in-place.

>>> for ldd in  list_data_dictionary:
...    ldd.update(*ist_common_dictionary)
    
>>> list_data_dictionary
[{'name': 'john', 'id': '1', 'Gender': 'M', 'Age': '25'},
 {'name': 'albert', 'id': '2', 'Gender': 'M', 'Age': '25'},
 {'name': 'jasper', 'id': '3', 'Gender': 'M', 'Age': '25'},
 {'name': 'guillaume', 'id': '4', 'Gender': 'M', 'Age': '25'}]
  • Related