Iterating over dictionaries in list - Python
Question: Similar to my last question: Is there a one-liner/Pythonic (the former doesn't
necessarily imply the latter, I know) way to write the following nested for
loop?

    
    
    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
    

I've tried

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

but I've been given a 'reference before assignment' error, which makes sense,
I think. Any suggestions? Thanks!


Answer: This isn't a one-liner, but achieves what you're trying to do neatly and
clearly:

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

Alternatively, you can protect against `i['some_key']` not being present with:

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

or against `i['some_key']` not being iterable with e.g.:

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

on the other hand, if it turns out your dictionary doesn't have the
appropriate key or the value isn't iterable, you might prefer to find out
directly!

I don't know what the data you're playing with represents, so can't make
suggestions, but better variable names would probably be helpful.

