0

The below piece of code is giving me an exception -

success_set = set()
for r in data:
  try: 
    q3 = "UPDATE tab_urls SET url_uploaded='1', url_uploaded_msg='%s' WHERE url = '%s';" %(r['verbose_msg'], r['url'])
    if conn.Execute(q3):
      success_set.add(r)
      logStr = "SUCCESS! Updated database!"
    else:
      logStr = "ERROR! Couldn't update database!"
    cUploaded += 1
  except Exception, e:
    logStr = "Invalid URL: " + str(r['url']) + " | Exception: " + str(e)
for url in batch_set.difference(success_set):
  q2 = "UPDATE tab_urls SET url_invalid = '1' WHERE url = '%s' AND url_month = 's';" %(url, filename)
  conn.Execute(q2)
  cInvalidURLs += 1

which is -

Invalid URL: <URL> | Exception: unhashable type: 'dict'

Can anyone tell me what I'm doing wrong here, and how to correct it? Thanks!

harry04
  • 900
  • 2
  • 9
  • 21
  • url could be a dictionary object but not string. What is the structure of data variable? – KiranM Dec 03 '17 at 02:22
  • You are trying to add `r` to a `set()`, but `r` is a dictionary, which is a mutable type. Mutable types are unhashable and only hashable types can be added to a set. – Craig Dec 03 '17 at 02:30
  • data is a list containing all the features of all the URLs uploaded, eg. u'url', u'response_code', u'verbose_message' etc. – harry04 Dec 03 '17 at 02:31
  • `data` is a list, but it's elements are dictionaries, otherwise you couldn't do `r['verbose_msg']`. – Craig Dec 03 '17 at 02:34
  • You can fix this error by converting `r` to a `frozenset()`, as stated in this answer: https://stackoverflow.com/a/13264725/7517724 – Craig Dec 03 '17 at 02:36
  • Yep, you're right! It's a dictionary. But, how can I do a set difference (edited above) if I change `success_set.add(r)` ? Can I do that with a frozenset? – harry04 Dec 03 '17 at 02:41
  • @harry04 - I have no idea what `batch_set` contains, so I don't know for sure. But, if it is a `set`, then it can't contain dictionaries either, so you might as well give it a try. – Craig Dec 03 '17 at 02:45
  • The question is not a duplicate. Adding dicts to sets is not handled in the redirected to page. – rwst Dec 29 '20 at 09:02

0 Answers0