您可以通过对索引进行降序排序来优化这一点,然后您可以使用dict.pop(key,None) 一次检索并删除键/值,但我决定不这样做,按照indices 中出现的顺序附加值。
from collections import OrderedDict
from pprint import pprint
def mergeEm(d,indices,key):
"""Merges the values at index given by 'indices' on OrderedDict d into a list.
Appends this list with key as key to the dict. Deletes keys used to build list."""
if not all(x < len(d) for x in indices):
raise IndexError ("Index out of bounds")
vals = [] # stores the values to be removed in order
allkeys = list(d.keys())
for i in indices:
vals.append(d[allkeys[i]]) # append to temporary list
d[key] = vals # add to dict, use ''.join(vals) to combine str
for i in indices: # remove all indices keys
d.pop(allkeys[i],None)
pprint(d)
fields= OrderedDict([
("Sample Code", "Vendor Sample ID"),
("Donor ID", "Vendor Subject ID"),
("Format", "Material Format"),
("Sample Type", "Sample Type"),
("Age", "Age"),
("Gender", "Gender"),
("Ethnicity/ Race", "Race"),
("Sample Type", "Sample Type"),
("Organ", "Organ"),
("Pathological Diagnosis", "Diagnosis"),
("Detailed Pathological Diagnosis", "Detailed Diagnosis"),
("Clinical Diagnosis/Cause of Death", "Detailed Diagnosis option 2"),
("Dissection", "Dissection"),
("Quantity (g, ml, or ug)", "Quantity"),
("HIV", "HIV"),
("HEP B", "HEP B")
])
pprint(fields)
mergeEm(fields, [5,4,2], "tata")
输出:
OrderedDict([('Sample Code', 'Vendor Sample ID'),
('Donor ID', 'Vendor Subject ID'),
('Format', 'Material Format'),
('Sample Type', 'Sample Type'),
('Age', 'Age'),
('Gender', 'Gender'),
('Ethnicity/ Race', 'Race'),
('Organ', 'Organ'),
('Pathological Diagnosis', 'Diagnosis'),
('Detailed Pathological Diagnosis', 'Detailed Diagnosis'),
('Clinical Diagnosis/Cause of Death',
'Detailed Diagnosis option 2'),
('Dissection', 'Dissection'),
('Quantity (g, ml, or ug)', 'Quantity'),
('HIV', 'HIV'),
('HEP B', 'HEP B')])
OrderedDict([('Sample Code', 'Vendor Sample ID'),
('Donor ID', 'Vendor Subject ID'),
('Sample Type', 'Sample Type'),
('Ethnicity/ Race', 'Race'),
('Organ', 'Organ'),
('Pathological Diagnosis', 'Diagnosis'),
('Detailed Pathological Diagnosis', 'Detailed Diagnosis'),
('Clinical Diagnosis/Cause of Death',
'Detailed Diagnosis option 2'),
('Dissection', 'Dissection'),
('Quantity (g, ml, or ug)', 'Quantity'),
('HIV', 'HIV'),
('HEP B', 'HEP B'),
('tata', ['Gender', 'Age', 'Material Format'])])