在python中,通过DICT列表中的单个字段进行迭代是否容易?

在python中,通过DICT列表中的单个字段进行迭代是否容易?,python,list,dictionary,Python,List,Dictionary,我已经看过了,但这与我想问的问题不同 考虑这个例子: oldpaths = [ {'dir': '/path3' }, {'dir': '/path1' }, {'dir': '/path2' }, {'dir': '/path4' }, ] nowpaths = [ '/path1', '/path2', '/path3', '/path5', ] print("Check missing A:") missp1=0 for idird in oldpath

我已经看过了,但这与我想问的问题不同

考虑这个例子:

oldpaths = [
  {'dir': '/path3' },
  {'dir': '/path1' },
  {'dir': '/path2' },
  {'dir': '/path4' },
]

nowpaths = [
  '/path1',
  '/path2',
  '/path3',
  '/path5',
]

print("Check missing A:")
missp1=0
for idird in oldpaths:
  if idird['dir'] not in nowpaths:
    missp1+=1
    print(missp1, idird['dir'])

print("Check missing B:")
missp2=0
for idirs in nowpaths:
  found = False
  for idird in oldpaths:
    if idirs == idird['dir']:
      found = True
      break
  if not(found):
    missp2+=1
    print(missp2, idirs)
它按预期打印:

Check missing A:
(1, '/path4')
Check missing B:
(1, '/path5')
但是,请注意,在第一种情况下,如果idird['dir']不在nowpaths:中,我可以只说
,然后处理它-但在第二种情况下,我必须通过dict列表进行显式循环,等等

如果我可以限制自己只在dict中查找单个字段,那么对于dict列表,有没有比这更简单的语法?如果IDIR不在oldpath['dir']:
,我可以想象类似于
的情况,但不幸的是,“TypeError:列表索引必须是整数,而不是str”…

found = False
for idird in oldpaths:
    if idirs == idird['dir']:
        found = True
        break
if not(found):
可以使用生成器表达式重写:

if not any(idirs == idird['dir'] for idird in oldpaths):
但是,一个更有效的解决方案(特别是如果您在
nowpaths
中有许多路径)是从旧路径中创建一组目录(并在for循环之外这样做):


您可以使用列表理解来缩短代码:

print("Check missing B:")
missp2=0
for idirs in nowpaths:
  if idird not in [oldpath['dir'] for oldpath in oldpaths]:
    missp2+=1
    print(missp2, idirs)

非常感谢您的回答,@DavidRobinson-感谢关于效率的说明。干杯非常感谢您的回答,@VaughnCato-请记住,列表理解在这里也很有用。干杯
print("Check missing B:")
missp2=0
for idirs in nowpaths:
  if idird not in [oldpath['dir'] for oldpath in oldpaths]:
    missp2+=1
    print(missp2, idirs)