I have this list:
address_table3 = [(1, ['21 South Main']), (2, ['1560 West St']), (3, ['1900 Broadway'])]
I want to convert it to a dictionary with the address as key and integer as value.
When I try to convert, I get an error:
TypeError: unhashable type: 'list'
I have tried dict comprehension and other ideas:
{k: v for k, v in zip(address_table3.values(), address_table3.keys())}
but nothing is working.
The dict
constructor will take a list of tuples where the first item in each tuple is the key and the second is the value. Yours are exactly backward from that. Also, the string you want to use as a key is in a list, which can't be used as a dictionary key and is the source of your error. So, you can write a generator expression to switch them around, extract the actual key from its list, and pass that to dict
.
dict((t[1][0], t[0]) for t in address_table3)
Or unpack the tuple into separate variables and do the same:
dict((k[0], v) for (v, k) in address_table3)
If there is any possibility that there might be more than one item in the list you're using as a key, you could use str.join
to concatenate them all into one string. The example here separates the individual items with newlines, but you could use spaces or any other character(s).
dict(('\n'.join(k), v) for (v, k) in address_table3)