user4659009
user4659009

Reputation: 685

Create a dictionary using comprehension with nested for loops

I have a nested for loop in which I am setting the key, value for my new dictionary. Having found out about list comprehensions, I'm wondering if it's possible to use the same logic for a dictionary.

My attempt at one line comprehension for the dictionary which currently fails:

dict_contract_name_id = {each_contract: each_contract.id for each_inuring_layer in context.program_obj.inuringLayers for each_contract in each_inuring_layer.contracts}

It fails by saying TypeError: unhashable type: 'ContractWithId'.

Actual code I'm trying to convert to one line comprehension:

dict_contract_name_id = {}
for each_inuring_layer in context.program_obj.inuringLayers:
    for each_contract in each_inuring_layer.contracts:
        if each_contract.name in contracts:
            dict_contract_name_id[each_contract.name] = each_contract.id

Upvotes: 1

Views: 61

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125058

You forgot the .name attribute, as well as the if filter:

dict_contract_name_id = {
    each_contract.name: each_contract.id
    for each_inuring_layer in context.program_obj.inuringLayers
    for each_contract in each_inuring_layer.contracts
    if each_contract.name in contracts}

You tried to use the each_contract object as a key, and not just the name.

Upvotes: 2

Related Questions