简体   繁体   English

如何获取键前和键后的值

[英]How to get the values before a key and after a key

I have dictionary below我下面有字典

{'1': {'Col1': 'Val1', 'Col2': 'Val2', 'output': 'Out1'},
 '2': {'Col1': 'Val1', 'Col2': 'Val2', 'output': 'Out1'},
 '3': {'Col1': 'Val1', 'Col2': 'Val2', 'output': 'Out1'},
 '4': {'Col1': 'Val1', 'Col2': 'Val2', 'output': 'Out1'}}

I need to get the values before the key output我需要在键output之前获取值

since dictionary is unordered i have converted into below由于字典是无序的,我已转换为以下

              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')]))])

Expected out is below, need to extract the values before output预期输出低于,需要在output前提取值

{'1': ['Val1', 'Val2'],
'2': ['Val1', 'Val2'],
'3': ['Val1', 'Val2'],
'4': ['Val1', 'Val2']}

Expected out is below, need to extract the values after the output key预期输出如下,需要提取output键后的值

{'1': [],
'2': [],
'3': [],
'4': []}

Sample dictionary for testing用于测试的示例字典

{'1': {'Col1': 'Val1', 'output': 'Out1', 'test': 'Out1'},
 '2': {'Col1': 'Val1', 'output': 'Out1', 'test': 'Out1'},
 '3': {'Col1': 'Val1','output': 'Out1'},
 '4': {'Col1': 'Val1', 'output': 'Out1'}}

Expected out is below, need to extract the values before output预期输出低于,需要在output前提取值

{'1': ['Val1'],
'2': ['Val1'],
'3': ['Val1'],
'4': ['Val1']}

Expected out is below, need to extract the values after the output key预期输出如下,需要提取output键后的值

{'1': ['Out1'],
'2': ['Out1'],
'3': [],
'4': []}

You can iterate over items using an iterator and appending to before list.您可以使用迭代器迭代项目并附加到列表before When the key you are looking for is found, break from that loop and then iterate again using that same iterator to read the values for the after list.当找到您要查找的键时, 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)

Gives:给出:

OrderedDict([('1', ['Val1', 'Val2']), ('2', ['Val1', 'Val2']), ('3', ['Val1', 'Val2']), ('4', ['Val1', 'Val2'])])
OrderedDict([('1', []), ('2', []), ('3', []), ('4', [])])

You might also raise an exception if the key you are looking for is never found ( break never executed).如果从未找到您要查找的键( break从未执行),您也可能会引发异常。 For example:例如:

    ...
    for k, v in it:
        if k == key:
            break
        before_vals.append(v)
    else:
        raise RuntimeError(f'The key {key} was not found')
    ...

You can use dict comprehension:您可以使用字典理解:

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']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM