我有以下内容:字典列表和字典,其中键是我的字典列表中键“userid”的值。我想额外获取字典中的数据,并根据用户 ID 是否匹配将其添加到每个字典中。以下是我的示例数据和我尝试过的内容。
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"}]
答案 0 :(得分:0)
如果我正确理解了您的问题,我似乎想出了一个非常简单的解决方案。
我唯一编辑的是 combine 函数,它看起来像这样:
def combine(data, extra):
data_new = data.copy()
for i in range(len(data_new)):
if data_new[i]['userid'] in extra:
data_new[i].update(extra[data_new[i]['userid']])
return data_new
您的代码中的两个主要问题是:
另外,这不是什么大事,但似乎没有必要复制额外字典,因为在此特定函数中您没有对其进行任何更改。
P.S.我对回答很陌生,所以我真的希望这会有所帮助
答案 1 :(得分:0)
这个更丑
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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()
ids = list(extra.keys())
for value in data_new:
indexx=data_new.index(value)
for valuez in value:
if value[valuez] in ids:
z={**data[indexx],**(extra[value[valuez]])}
data_new[indexx]=z
return data_new
pippo = combine(data, extra)
print(pippo)
永远不会少回报
[{'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
并使用
indexx=data_new.index(value)
因为忘记了 len(list) 并且无法通过索引访问列表 ;-)