简体   繁体   中英

TypeError: unhashable type: 'list'

I am running into following error with below piece of code, basically below is what I am trying to do, how can I modify my code without changing the original goal...

  1. if any of the values is a key with no values remove that line from the input
  2. if any of the values is a key with values, for each value (which is key) recursively check for its values until there are none and remove the duplicate lines...a sample input and output is shown below:

      KEY VALUES 353311 344670 332807 353314 338169 334478 334478 123456 34567 123456 98670 34567 11111 353314 353311 348521 350166 350168 350169 350170 350166 348521 350168 348521 350169 348521 350170 348521 EXPECTED OUTPUT 344670 332807 353314 353311 338169 334478 123456 34567 98670 11111 348521 350166 350168 350169 350170 

    Code:-

     from collections import OrderedDict def main (): with open('gerrit_dependencylist.txt') as f: dic = OrderedDict() seen = set() for line in f: #print dic,line spl = line.split() #print "SPL" #print spl if len(spl) == 1: key = spl[0] v = '' else: print "LINE" print line key, v = spl[0], spl[1:] for value in v: if value in dic and dic[value] == [""]: del dic[v] for k1,v1 in dic.iteritems(): if key in v1: dic[k1].append(v) break else: dic[key] = [v] if __name__ == '__main__': main() 

OUTPUT:-

    LINE
    332807 353314

    LINE
    338169 334478

    LINE
    334478 123456 34567

Traceback (most recent call last):
  File "tesst.py", line 29, in <module>
    main()
  File "tesst.py", line 21, in main
    del dic[v]
  File "/usr/lib/python2.7/collections.py", line 67, in __delitem__
    dict_delitem(self, key)
TypeError: unhashable type: 'list'

The variable v in this expression:

key, v = spl[0], spl[1:]

is a list with the remaining values. You cannot use a list to index a dictionary, so this:

del dic[v]

will fail. Looking at the code logic, you probably want to do this anyway:

for value in v:
   if ....
       del dic[value]

You're trying to index the dictionary using a list as a key. Replace the line in the error, del dic[v] with del dic[value] - assuming that's what you meant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM