-1

I wrote this Python script

with open('survey_data/survey_results_public.csv', encoding='utf-8') as f:
    csv_reader = csv.DictReader(f)

    dev_type_info = {}

    for line in csv_reader:
        dev_types = line['DevType'].split(';')

        for dev_type in dev_types:
            dev_type_info.setdefault(dev_type_info, {
                'total': 0,
                'language_counter': Counter()
            })

but I get this error

> TypeError                                 Traceback (most recent call
> last) <ipython-input-34-0dd498f86be7> in <module>
>      14             dev_type_info.setdefault(dev_type_info, {
>      15                 'total': 0,
> ---> 16                 'language_counter': Counter()
>      17             })
> 
> TypeError: unhashable type: 'dict'

can anyone shade light upon this error, what is it and how do I solve it? Thank you

Mir Stephen
  • 1,758
  • 4
  • 23
  • 54
  • 1
    `dict` can't be key. Why are you using a dictionary as a key in itself? even if you could it doesn't make much sense. – Guy Nov 17 '19 at 06:00
  • Maybe it's a data type conversion problem. See this article: http://net-informations.com/python/iq/unhashable.htm. – gsscoder Nov 17 '19 at 06:03
  • Possible duplicate of [TypeError: unhashable type: 'dict'](https://stackoverflow.com/questions/13264511/typeerror-unhashable-type-dict) – AMC Nov 17 '19 at 06:58
  • Why are you using `setdefault` over `defaultdict`? – AMC Nov 17 '19 at 06:58
  • i fixed that now it is working fine – Mir Stephen Nov 17 '19 at 13:47

2 Answers2

2

I think you meant :

for dev_type in dev_types:
  dev_type_info.setdefault(dev_type, {
    'total': 0,
    'language_counter': Counter()
   })

as the usage for dict.setdefault is a key as the first parameter, not the dict itself.

dict.setdefault(key, default=None)
Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24
0

You are getting this error because You're trying to use a dict as a key to another dict. Correct the below line of code:

dev_type_info.setdefault(dev_type_info, { ..
Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36