TypeError: unsupported operand type (s) for /: 'dict_values' and 'int'

1

Every time I run this code in python I get the error:

  

TypeError: unsupported operand type (s) for /: 'dict_values' and 'int' .

How could I solve it?

def analizar():
    dic = {}
    fClasses = open(nomFileClasses,'r')
    lna = fClasses.readlines()
    for ln in lna:
        if not(ln in dic):
            dic[ln]=1
        else:
            dic[ln]=dic[ln]+1
    values = np.array(dic.values())
    std_desv = np.std(values,dtype=np.float32)
    return std_desv

Thank you very much.

    
asked by Carla 19.03.2017 в 21:02
source

1 answer

1

In Python 3.x unlike Python 2.x the method dict.values() returns a objeto de tipo view ( dict_values ) and not a list. NumPy accepts dict_values when building the array but we do not get what we expected (an array of dictionary values). To fix it simply transform it into a list before passing it to the constructor of np.array :

list(dic.values())

This way if you will be created an array of integers on which you can calculate the std without problems.

The code is therefore:

def analizar():
    dic = {}
    fClasses = open(nomFileClasses,'r')
    lna = fClasses.readlines()
    for ln in lna:
        if not(ln in dic):
            dic[ln]=1
        else:
            dic[ln]=dic[ln]+1
    values = np.array(list(dic.values()))
    std_desv = np.std(values,dtype=np.float32)
    return std_desv

With this the problem should disappear.

As a note, if you do not confuse me, you are using the dictionary to count the number of occurrences of the different chains that returns readlines() , you can obtain the same result efficiently if so using collections.Counter() from the standard Python library:

import numpy as np
from collections import Counter

def analizar():
    fClasses = open('nomFileClasses.txt','r')
    lna = fClasses.readlines()
    dic = Counter(lna)
    values = np.array(list(dic.values()))
    std_desv = np.std(values,dtype=np.float32)
    return std_desv
    
answered by 19.03.2017 / 22:32
source