Home > database >  Strange behavior: list comprehension with dictionaries
Strange behavior: list comprehension with dictionaries

Time:03-01

I recently encountered (something similar to) the following. Consider the following list of dictionaries.

dics = [{'a':'a',
         'b':[{'a':'a'},
              {'a':'b'},
              {'a':'c'},
              {'a':'d'},
              {'a':'e'}]},
        {'a':'a',
         'b':[{'a':'a'}]}]

I want a list of the values corresponding to the key 'a' in all innermost dictionaries, which are in turn listed under the key 'b'. Of course, we could achieve this with the following for loop:

result = []
for d1 in dics:
    for d2 in d1['b']:
        result.append(d2['a'])

However, I was hoping to do this using list comprehension. Now, I found that

result = [[d2['a'] for d2 in d1['b']] for d1 in dics]

results in the list [['a', 'b', 'c', 'd', 'e'], ['a']], so it would stand to reason (or so I thought) that

result = [d2['a'] for d2 in d1['b'] for d1 in dics]

would yield the "flattened" list ['a', 'b', 'c', 'd', 'e', 'a'], which is what I want. What I actually get, however, is the the list ['a', 'a']. What's going on here?

CodePudding user response:

You have the inner and outer loop of the double loop backwards. Try it with:

result = [d2['a'] for d1 in dics for d2 in d1['b']]

Actually, it's surprising that

[d2['a'] for d2 in d1['b'] for d1 in dics]

didn't result in a NameError because in the outer loop d1['b'] is undefined.

  • Related