我有以下内容:字典列表和一个字典,其中键是字典列表中键“userid”的值。我想额外获取dictionary中的数据,并根据userid是否匹配将其添加到每个dictionary中。下面是我的示例数据和我尝试过的内容
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
上述结果
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"}}]
我想要的是:
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"}]
如果我正确理解了你的问题,我似乎想出了一个非常简单的解决办法。
我唯一编辑过的是合并函数和它看起来是这样的:
代码中的两个主要问题是:
另外,这不是什么大事,但似乎没有必要复制额外字典,因为在这个特定函数中,您没有对它做任何更改
顺便说一句,我对回答这个问题很陌生,所以我真的希望这能有所帮助
这个更难看
回报永不减少
使用字典合并,请参阅:How do I merge two dictionaries in a single expression in Python (taking union of dictionaries
使用
因为忘记了len(list)并无法通过索引访问列表;-)
相关问题 更多 >
编程相关推荐