Search code examples
pythoniteratordictionary-comprehension

make list of dictionaries overwriting one key entry from a list using iterators


I have the horrible feeling this will be a duplicate, I tried my best to find the answer already.

I have a dictionary and a list, and I want to create a list of dictionaries, using the list to overwrite one of the key values, like this:

d={"a":1,"b":10}      
c=[3,4,5] 
arg=[]
for i in c:
    e=d.copy()
    e["a"]=i
    arg.append(e)

this gives the desired result

arg
[{'a': 3, 'b': 10}, {'a': 4, 'b': 10}, {'a': 5, 'b': 10}]

but the code is ugly, especially with the copy command, and instead of one list I have 4 or 5 in my real example which leads to a huge nested loop. I feel sure there is a neater way with an iterator like

arg=[d *with* d[a]=i for i in c] 

where I'm not sure what to put in the place of the "with".

Again, apologies if this is already answered.


Solution

  • IIUC, you could do:

    d={"a":1,"b":10}
    c=[3,4,5]
    
    res = [{ **d, "a" : ci } for ci in c]
    print(res)
    

    Output

    [{'a': 3, 'b': 10}, {'a': 4, 'b': 10}, {'a': 5, 'b': 10}]
    

    The part:

    "a" : ci
    

    rewrites the value at the key "a" and **d unpacks the dictionary.