python for循环不迭代dict列表的所有索引

python for循环不迭代dict列表的所有索引,python,iterator,Python,Iterator,我试图遍历一个dict列表以找到匹配的字符串。 这对第一个索引有效,但对第二个索引无效 types = [{'type': '1'}, {'type': '2'}] #type = '1' type = '2' print(f'all types {types}') print(f'length {len(types)}') print(f'Getting type: {type}') for tp in types: print(f'current index {

我试图遍历一个dict列表以找到匹配的字符串。 这对第一个索引有效,但对第二个索引无效

types = [{'type': '1'},
         {'type': '2'}]
#type = '1'
type = '2'

print(f'all types {types}')
print(f'length {len(types)}')
print(f'Getting type: {type}')

for tp in types:
    print(f'current index {tp}')
    if tp['type'] == type:
        print(f'found {type}')
        foundType = tp
    print(f'last match is {foundType}')

为什么这不起作用?

在第一次迭代中,您的if语句不正确,因此当您在最后打印时,
foundtype
不会启动,因此它不知道打印什么,正如@makr3la所提到的,下面实现了更好的命名约定并修复了@matman9提供的解释

types = [{'type': '1'},
         {'type': '2'}]
find_this = '2'
for this_dict in types:
    if this_dict['type'] == find_this:
        print('found '+find_this)

尽量避免将
类型
作为变量名,因为它是Python中的内置函数。啊,谢谢,这只是我这边的一个缩进错误