检查列表中每个字典中的参数值是否是连续的

Sam*_*ira 3 python dictionary list

我想检查当前是否id等于最后id一个+1,(这应该适用于列表中添加的任意数量的类似字典)

代码

listing = [
    {
        'id': 1,
        'stuff': "othervalues"
    },
    {
        'id': 2,
        'stuff': "othervalues"
    },
    {
        'id': 3,
        'stuff': "othervalues"
    }
]

for item in listing :
    if item[-1]['id'] == item['id']+1:
        print(True)
Run Code Online (Sandbox Code Playgroud)

输出

Traceback (most recent call last):
  File "C:\Users\samuk\Desktop\Master\DV\t2\tester.py", line 10, in <module>
    if item[-1]['id'] == item['id']+1:
KeyError: -1
Run Code Online (Sandbox Code Playgroud)

期望的结果

True
Run Code Online (Sandbox Code Playgroud)

或者,万一失败,

False
Run Code Online (Sandbox Code Playgroud)

Ch3*_*teR 5

要检查所有ids 是否按顺序排列,我们可以enumerate在此处使用。

def is_sequential(listing):
    start = listing[0]['id']
    for idx, item in enumerate(listing, start):
        if item['id'] != idx:
            return False
    return True
Run Code Online (Sandbox Code Playgroud)