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? –