Home > other >  How can I return what I expect from nested list or dictionary comprehension?
How can I return what I expect from nested list or dictionary comprehension?

Time:07-11

I've tried two different approaches to this problem.

Here's a nested list comprehension that I expect to return a list of tuples with each tuple containing 2 items.

table_info = [[(tag['Value'], table['RouteTableId']) for tag in table['Tags'] if tag['Key'] == "Name"] for table in tables]

What I'm getting instead is a list of tuples with each tuple containing 1 item with both variables.

So I tried to use a nested dictionary comprehension that should return a dictionary with key "tag['Value']" and value "table['RouteTableId']".

table_info = {{tag['Value']: table['RouteTableId'] for tag in table['Tags'] if tag['Key'] == "Name"} for table in tables}

Instead, I'm receiving this error: TypeError: unhashable type: 'dict', which essentially means I'm trying to use both values as the key.

It seems in both cases that the comprehension is grouping both of the variables together as one item instead of two separate items, but I cannot understand why. Any help is greatly appreciated.

CodePudding user response:

What I'm getting instead is a list of tuples with each tuple containing 1 item with both variables.

Not quite -- what you're getting is a list of lists, with each list containing the list of tuples for a single tag. That's because you have two nested list comprehensions ([[]]).

To fix that and get the single list you're after, create a single list comprehension with a nested generator:

table_info = [
    (tag['Value'], table['RouteTableId'])
    for table in tables
    for tag in table['Tags']
    if tag['Key'] == "Name"
]

Note that there is only a single [] now, meaning you'll get a single list instead of nested lists.

The two for statements are ordered from outermost to innermost, similar to the equivalent nested for loop construction:

table_info = []
for table in tables:
    for tag in table['Tags']:
        if tag['Key'] == "Name":
            table_info.append((tag['Value'], table['RouteTableId']))
  • Related