How to solve TypeError: unhashable type 'list'

Tony Roczz picture Tony Roczz · Nov 18, 2015 · Viewed 12.8k times · Source

I have two lists I would like to modify a particular content of the first list and send the output but when I try to modify it, am getting an error TypeError: unhashable type: 'list'. I am using python with mongodb.

The two lists are

data = [{"id" : ["5630baac3f32df134c18b682","564b22373f32df05fc905564"],"phone" : ["9988776655","9638527410"], "Request": "Support staff", "Date": "19-11-2015"}]
test = [{"phone" : "9638527410", "id": "5630baac3f32df134c18b682"}]
id = {}
for info in chain(data, test):
    id.setdefault(info['id'], {}).update(info)
res = list(id.values())
print(res)

The required output is

[{"phone" : "9638527410", "id": "5630baac3f32df134c18b682", "Request": "Support staff", "Date": "19-11-2015"}]

What is the mistake I am making here?

Can anyone guide me how I can get the desired output.

Answer

Mangu Singh Rajpurohit picture Mangu Singh Rajpurohit · Nov 18, 2015

You are using list as an key in the dictionary. List is not a hashable type in python. So, it can not be used as key in the dictionary. Only hashable types such as tuple, strings, numbers can be used as key in the dictionary.