Cybernetic
Cybernetic

Reputation: 13334

Subsetting a dictionary in Python using a list of keys - unhashable error

I am trying to subset a dictionary in python by using the keys in a list. Here is what I have:

sub_set = dict((k, my_dict[k]) for k in tuple(my_list))

But I am getting the error:

TypeError: unhashable type: 'list'

But I thought converting it to a tuple first would have solved that.

Upvotes: 0

Views: 206

Answers (2)

Sylvain Leroux
Sylvain Leroux

Reputation: 51980

List are unhashable. Tuple are hashable. Both are iterable.

I thought converting it to a tuple first would have solved that.

Assuming from your example that my_list is a "list of list", probably you don't put the tuple() call at the right place:

sub_set = dict((tuple(k), my_dict[tuple(k)]) for k in my_list)
#               ^^^^^^^^          ^^^^^^^^
#      convert the list k to a tuple

Or better:

sub_set = dict((k, my_dict[k]) for k in map(tuple,my_list))
#                                       ^^^^^^^^^^^^^^^^^^
#                                   map *inner* lists to tuples

See:

>>> my_dict = {(1, 2): "1;2", (2, 3): "2;3", (3, 4): "3;4" }
>>> my_list = [[1, 2], [2, 3]]
>>> sub_set = dict((k, my_dict[k]) for k in map(tuple,my_list))
>>> sub_set
{(1, 2): '1;2', (2, 3): '2;3'}

Upvotes: 2

André Laszlo
André Laszlo

Reputation: 15537

Works for me. What's in my_list?

In [2]: my_dict = {'foo': 1, 'bar': 2, 'baz': 3}
In [3]: my_list = ['foo', 'baz']
In [4]: sub_set = dict((k, my_dict[k]) for k in tuple(my_list))
In [5]: sub_set
Out[5]: {'baz': 3, 'foo': 1}

Upvotes: 0

Related Questions