Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在列表Python中迭代字典_Python_Loops_Dictionary_Nested_Iteration - Fatal编程技术网

在列表Python中迭代字典

在列表Python中迭代字典,python,loops,dictionary,nested,iteration,Python,Loops,Dictionary,Nested,Iteration,与我的上一个问题类似:是否有一种单行程序/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 it

与我的上一个问题类似:是否有一种单行程序/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

但我被赋予了一个“分配前参考”的错误,我认为这是有道理的。有什么建议吗?谢谢

这不是一句简单的话,但却能干净利落地实现您的目标:

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
另一方面,如果发现您的字典没有相应的键或值不可编辑,您可能更愿意直接查找


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

您在
做点什么
区域尝试做些什么?想想这样的事情:
[elm for elm in some_list if elm['key']==value]
do something(做某事)很重要检查j是否符合某些标准,如果符合,则更改i值中的另一个键。例如:对于某些列表中的I:对于I['some_key']中的j:如果j在另一个列表中:I['other_key']=True#执行添加的操作。很抱歉这假定
i[“some_key”]
是一个iterable,并且所有键都存在于所有dicts@PadraicCunningham没错,但原作也是如此!我将编辑以添加一个稍微更健壮的方法。仍然会被
some_-list=[{“some_-key”:3,“另一个_-key”:False}]
@PadraicCunningham抓住,然后您可以添加
尝试:除了TypeError
,但是如果
'some_-key'
的值不合适,是否应该分配
'another_-key'
?在这种情况下,OP可能更喜欢显式错误,因为它表明输入不是他们所认为的。