1
我有一个列表dicts
在那里我需要合并包含相同的ID
键/ val的多个字典。我目前所做的并不奏效,它只输出一个新格式的字典,但格式正确,但我需要将所有合并的字典放在一个新列表中(或有变异的地方,我并不太在乎) )。循环列表的字典和结合具有相同ID的字典
该列表并没有真正具有相同ID的多少个字符可能存在的最小值或最大值,它是另一个变化函数的输出。
这里就是我有类型的字典的
列表:
# actual ID's are longer and alphanumeric, this is for simplicity.
# dicts with same ID will also have the same 'taskConstraint',
# but that is a side effect and can't be used as a filter
test_update_list = [
{"ID":"1","taskConstraint": "FIXT","plannedCompletionDate":"2017-07-29","constraintDate":"2017-07-29"},
{"ID":"1","taskConstraint": "FIXT","plannedStartDate":"2017-07-25","constraintDate":"2017-07-25"},
{"ID":"2","taskConstraint": "MSO","plannedCompletionDate":"2017-07-29","constraintDate":"2017-07-29"},
{"ID":"1","taskConstraint": "FIXT","noteText": "Note update text"},
{"ID":"2","taskConstraint": "MSO","noteText": "Note update text"},
{"ID":"3","taskConstraint": "MFO","noteText": "Note update text"},
{"ID":"3","taskConstraint": "MFO","plannedStartDate":"2017-07-25","constraintDate":"2017-07-25"}]
所需的输出:
desired_output = [
{"ID":"1","taskConstraint":"FIXT","plannedStartDate":"2017-07-25","constraintDate":"2017-07-25","plannedCompletionDate":"2017-07-29"},
{"ID":"2","taskConstraint": "MSO","plannedCompletionDate":"2017-07-29","constraintDate":"2017-07-29","noteText": "Note update text"},
{"ID":"3","taskConstraint": "MFO","plannedStartDate":"2017-07-25","constraintDate":"2017-07-25","noteText": "Note update text"}]
我的可怕和不正确迄今为止尝试:
test_update_list = [
{"ID":"1","taskConstraint": "FIXT","plannedCompletionDate":"2017-07-29","constraintDate":"2017-07-29"},
{"ID":"1","taskConstraint": "FIXT","plannedStartDate":"2017-07-25","constraintDate":"2017-07-25"},
{"ID":"2","taskConstraint": "MSO","plannedCompletionDate":"2017-07-29","constraintDate":"2017-07-29"},
{"ID":"1","taskConstraint": "FIXT","noteText": "Note update text"},
{"ID":"2","taskConstraint": "MSO","noteText": "Note update text"},
{"ID":"3","taskConstraint": "MFO","noteText": "Note update text"},
{"ID":"3","taskConstraint": "MFO","plannedStartDate":"2017-07-25","constraintDate":"2017-07-25"}]
new_update_list = []
for task in test_update_list:
if len(new_update_list) > 0 and task not in new_update_list:
for new_task in new_update_list:
if task['ID'] == new_task['ID']:
new_task = { **task, **new_task }
else:
new_update_list.append(task)
print(new_update_list)
,输出...
[{'ID': '1', 'plannedCompletionDate': '2017-07-29', 'constraintDate': '2017-07-29', 'taskConstraint': 'FIXT'}]
您在所需的输出中重复键:'constraintDate'。 –
糟糕,看起来只是第一个。固定。 – DjH
为什么'NoteText':'Note update text''丢失ID 1? –