mel mel - 3 years ago 167
Python Question

Create a list of dictionaries from a global variable using map or comprehension list python

I have a dictionary as a global variable and a list of string:

GLOBAL = {"first": "Won't change", "second": ""}
words = ["a", "test"]

My goal is to create the following list:

[{"first": "Won't change", "second": "a"}, {"first": "Won't change", "second": "test"}]

I can do it with the following code:

result_list = []
for word in words:
dictionary_to_add = GLOBAL.copy()
dictionary_to_add["second"] = word

My question is how can I do it using a comprehension list or using the map() function

Answer Source

Pretty sure you can do this in one ugly line. Assuming you use immutables as values, otherwise you'd have to do a deep copy which is also possible:

[GLOBAL.copy().update(second=w) for w in word]

Or even better (Python 3 only)

[{**GLOBAL, "second": w} for w in word]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download