I have the following: list of dictionaries and a dictionary where the key is the value of key "userid" in my list of dictionaries. I want to take the data within dictionary extra and add it to each dictionary based on if the userid matches. Below is my sample data and what I have tried.
data = [{'date':'2021-01-01',
'userid': 'ABC123',
'name': 'John Smith',
'age': 15},
{'date':'2021-01-10',
'userid': 'DEF123',
'name': 'Jane Doe',
'age': 19}]
extra = {'ABC123' : {"favorite sport": "basketball",
"favorite color": "red"},
'DEF123': {"favorite sport": "soccer",
"favorite color": "yellow"}}
def combine(data, extra):
data_new = data.copy()
extra_new = extra.copy()
ids = list(extra_new.keys())
output = []
for value in data_new:
value.update(extra_new)
output.append(value)
return output
The above results in
output = [{'date':'2021-01-01',
'userid': 'ABC123',
'name': 'John Smith',
'age': 15,
'ABC123' : {"favorite sport": "basketball",
"favorite color": "red"},
'DEF123': {"favorite sport": "soccer",
"favorite color": "yellow"}}
{'date':'2021-01-10',
'userid': 'DEF123',
'name': 'Jane Doe',
'age': 19,
'ABC123' : {"favorite sport": "basketball",
"favorite color": "red"},
'DEF123': {"favorite sport": "soccer",
"favorite color": "yellow"}}]
What I want is:
output = [{'date':'2021-01-01',
'userid': 'ABC123',
'name': 'John Smith',
'age': 15,
"favorite sport": "basketball",
"favorite color": "red"}
{'date':'2021-01-10',
'userid': 'DEF123',
'name': 'Jane Doe',
'age': 19,
"favorite sport": "soccer",
"favorite color": "yellow"}]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…