检查列表中的值是否在字典值字典中并返回索引

时间:2020-10-07 12:51:16

标签: python dictionary

假设我有一本以str键和dicts为值的字典:

{'one': {1: (3, [0.001, 0.003]), 2: (13, [0.005, 0.007]), 0: (4, [0.008, 0.008])}, 
'two': {0: (12, [0.01, 0.016]), 1: (6, [0.03, 0.036]), 2: (1, [0.04, 0.04])}}

如何检查值0.0015是否在嵌套dict内的每个值列表的范围内,即[0.001,0.003],[0.005,0.007]等),如果是,则返回“一个”或“二”以及键“一”或“二”的值的索引?

对于上述示例0.0015,我想返回['one',0],因为此值介于0.001和0.003之间,并且此范围[0.001,0.003]是从左到右位置的第一个

1 个答案:

答案 0 :(得分:0)

尝试一下:

d = {'one': {1: (3, [0.001, 0.003]), 2: (13, [0.005, 0.007]), 0: (4, [0.008, 0.008])},
     'two': {0: (12, [0.01, 0.016]), 1: (6, [0.03, 0.036]), 2: (1, [0.04, 0.04])}}

VAL = 0.0015
for k, v in d.items():
    for idx, (k1, v1) in enumerate(v.items()):
        pair = v1[1]
        if pair[0] <= VAL <= pair[1]:
            print(f'{k} {idx}')

输出

one 0