2 回答
TA贡献1797条经验 获得超4个赞
您可以使用迭代器迭代项目并附加到before列表。当找到您要查找的键时,break从该循环开始,然后使用同一迭代器再次迭代以读取列表的值after。
from collections import OrderedDict
d = OrderedDict([('1',
OrderedDict([('Col1', 'Val1'),
('Col2', 'Val2'),
('output', 'Out1')])),
('2',
OrderedDict([('Col1', 'Val1'),
('Col2', 'Val2'),
('output', 'Out1')])),
('3',
OrderedDict([('Col1', 'Val1'),
('Col2', 'Val2'),
('output', 'Out1')])),
('4',
OrderedDict([('Col1', 'Val1'),
('Col2', 'Val2'),
('output', 'Out1')]))])
def vals_before_and_after(od, key):
it = iter(od.items())
before_vals = []
for k, v in it:
if k == key:
break
before_vals.append(v)
after_vals = [v for k, v in it]
return before_vals, after_vals
before = OrderedDict()
after = OrderedDict()
for k, v in d.items():
before[k], after[k] = vals_before_and_after(v, 'output')
print(before)
print(after)
给出:
OrderedDict([('1', ['Val1', 'Val2']), ('2', ['Val1', 'Val2']), ('3', ['Val1', 'Val2']), ('4', ['Val1', 'Val2'])])
OrderedDict([('1', []), ('2', []), ('3', []), ('4', [])])
如果您正在查找的密钥从未找到(break从未执行过),您也可能会引发异常。例如:
...
for k, v in it:
if k == key:
break
before_vals.append(v)
else:
raise RuntimeError(f'The key {key} was not found')
...
TA贡献1828条经验 获得超13个赞
您可以使用字典理解:
dx = {k: list({i:x for i, x in v.items() if x != 'Out1'}.values()) for k,v in d.items()}
print(dx)
{'1': ['Val1', 'Val2'],
'2': ['Val1', 'Val2'],
'3': ['Val1', 'Val2'],
'4': ['Val1', 'Val2']}
添加回答
举报