【问题标题】:Iterating over dictionaries in list - Python迭代列表中的字典 - Python
【发布时间】:2014-09-26 21:47:24
【问题描述】:

与我的上一个问题类似:是否有一种单行/Pythonic(我知道,前者不一定暗示后者)方式来编写以下嵌套 for 循环?

some_list = # list of dictionaries
for i in some_list:
    for j in i['some_key']:
        if j is in another_list:
            i['another_key'] = True

我试过了

import itertools
for i,j in itertools.product(some_list,i):
    if j is in another_list:
        i['another_key'] = True

但我收到了“分配前的参考”错误,我认为这是有道理的。有什么建议?谢谢!

【问题讨论】:

  • 你想在do something区域做什么?
  • 想想类似:[elm for elm in some_list if elm['key'] == value]
  • #做某事很重要
  • 检查 j 是否满足某些条件,如果满足则更改 i 值中的另一个键。即:for i in some_list: for j in i['some_key']: if j is in another_list: i['another_key'] = True
  • # 添加一些东西。对不起!

标签: python loops dictionary nested iteration


【解决方案1】:

这不是单行的,而是简洁明了地实现了您想要做的事情:

for i in some_list:
    i['another_key'] = any(j in another_list for j in i['some_key'])

或者,您可以防止i['some_key'] 不在场:

for i in some_list:
    i['another_key'] = any(j in another_list for j in i.get('some_key', []))

或反对i['some_key'] 不可迭代,例如:

try:
    i['another_key'] = any(j in another_list for j in i['some_key'])
except TypeError:
    # whatever you want to do instead

另一方面,如果发现您的字典没有适当的键或值不可迭代,您可能更愿意直接查找!

我不知道您正在使用的数据代表什么,因此无法提出建议,但更好的变量名称可能会有所帮助。

【讨论】:

  • 这假定 i["some_key"] 是一个可迭代的并且所有键都存在于所有字典中
  • @PadraicCunningham 确实如此,但原版也是如此!我将进行编辑以添加一种更强大的方法。
  • 还是会被some_list = [{"some_key":3,'another_key':False}]抓到
  • @PadraicCunningham 那么你可以添加一个try: except TypeError 但如果'some_key' 的值不可迭代,那么'another_key' 是否应该被分配?在这种情况下,OP 可能更喜欢显式错误,因为它表明输入不是他们认为的那样。
猜你喜欢
  • 1970-01-01
  • 2015-09-28
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
相关资源
最近更新 更多