通过python中的dicts列表中的单个字段可以轻松迭代吗?

时间:2014-03-23 17:07:51

标签: python list dictionary

我已经看过selecting a single field from a list of dictionaries in python - Stack Overflow,但是我在这里问了一个不同的问题。

考虑这个例子:

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')

但是,请注意,在第一种情况下,我可以说if idird['dir'] not in nowpaths:并完成它 - 但在第二种情况下,我必须在dicts列表中进行显式循环等。

对于一个dicts列表,是否有比这更简单的语法,如果我可以限制自己只在dict中查找单个字段?我想象if idirs not in oldpaths['dir']:之类的东西,但遗憾的是" TypeError:list indices必须是整数,而不是str" ...

2 个答案:

答案 0 :(得分:1)

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中有很多路径)将是从oldpaths创建一组目录(并且在for循环之外这样做):

olddirs = set(idird['dir'] for idird in oldpaths)
for idirs in nowpaths:
    if not idirs in olddirs:

答案 1 :(得分:1)

您可以使用列表推导来缩短代码:

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)