Python 在字典列表中查找匹配项

问题描述 投票:0回答:6

我有一大堆字典。每个字典包含收集每个数据点时每个传感器的时间序列数据。我想知道特定传感器的索引位置和日期。所以,我可以更新传感器值。 我的代码:

big_list = [
dict({'sensor':12,'time':'2022-02-03','value':10}),
dict({'sensor':22,'time':'2022-02-03','value':12}),
dict({'sensor':32,'time':'2022-02-03','value':24}),
dict({'sensor':12,'time':'2022-02-04','value':17}),
dict({'sensor':22,'time':'2022-02-04','value':13}),
dict({'sensor':32,'time':'2022-02-04','value':21})]

# Find index of an item 
item_to_find = dict({'time':'2022-02-03','sensor':32})
# solution
big_list.index(item_to_find)

当前输出:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: {'sensor': 32, 'time': '2022-02-03'} is not in list

预期产出:

2
python list numpy dictionary numpy-ndarray
6个回答
1
投票

我知道这可能不是最有效的解决方案,但这是我能做的最好的。 :)

sensor = 32
time = '2022-02-03'

for item in big_list:
    if item.get('sensor') == sensor and item.get('time') == time:
        print(big_list.index(item))

1
投票

你可以试试

next()
+
enumerate()
:

idx = next(
    i for i, d in enumerate(big_list) if all(d[k] == v for k, v in item_to_find.items())
)
print(idx)

印花:

2

或:如果找不到该项目,您可以将默认参数添加到

next()

# returns None if the item is not found
idx = next(
    (i for i, d in enumerate(big_list) if all(d[k] == v for k, v in item_to_find.items())), None
)
print(idx)

1
投票

与@Andrej 相同的想法,但您可以使用 lambda 函数以获得更清晰的意图

same_time_and_sensor = lambda item: item['sensor'] == item_to_find['sensor'] and item['time'] == item_to_find['time']

index = next((i for i, item in enumerate(big_list) if same_time_and_sensor(item)), None)

print(index)

这里

next()
将返回第一场比赛的索引或
None
如果没有找到比赛。


1
投票

如果您正在寻找特定的

date
sensor
,您可以循环遍历列表中的每个字典并将匹配项的索引保存在索引列表中:

sensor = 32
date = '2022-02-03'

ind = []
for idx, dt in enumerate(big_list):
    if dt['sensor'] == sensor and dt['time'] == date:
        ind.append(idx)

print(ind)

1
投票

试试这个:

list(
    map(
        lambda x: {'time': x['time'], 'sensor': x['sensor']} == item_to_find,
        big_list
    )
).index(True)

说明:

  • 使用
    map()
    提取要比较的值,剥离
    value
  • 在被映射的函数中,与
    item_to_find
    进行比较-这将返回一个迭代器,它将为匹配产生
    True
    或为不匹配产生
    False
  • 使用
    list()
  • 将生成的迭代器转换为列表
  • True
    的这个列表中找到第一次出现并返回索引。

您可能还想看看

pandas
这使得所有这些都更容易处理。


0
投票

同时,我也在网上找到了一个答案:

solution_item = next(filter(lambda s: s['time']==item_to_find['time'] and s['sensor']==item_to_find['sensor'],big_list))

{'sensor': 32, 'time': '2022-02-03', 'value': 24}

解决方案索引

big_list.index(solution_item)

2
© www.soinside.com 2019 - 2024. All rights reserved.