2

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 ?

buran
  • 13,682
  • 10
  • 36
  • 61
  • That might depend on *how* you are using `deepcopy`. – Scott Hunter Oct 13 '21 at 13:01
  • It looks like you're trying to merge dictionaries, `deepcopy` is unlikely to be relevant. – Jasmijn Oct 13 '21 at 13:02
  • Is `list_common_dictionary` only ever going to contain one item? If so, why is that item wrapped in a list? If not, what is the desired behaviour if `len(list_common_dictionary) != 1`? – Jasmijn Oct 13 '21 at 13:05

2 Answers2

2

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.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • merging with `dict(**d1, **d2)`? Would it be less performant? – cards Oct 13 '21 at 13:08
  • I'm not sure but perhaps you could find the answer here https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-taking-union-of-dictiona – Dani Mesejo Oct 13 '21 at 13:10
  • 1
    from the link: the `dict` is faster, but at the expense of readability – cards Oct 13 '21 at 13:17
1

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'}]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30