Error: Collections.defaultdict' Object has in Python iteritems attribute

Asked

Viewed 232 times

2

When executing the code below the compiler returns the following message:

collections.defaultdict' object has no attribute 'iteritems'

I’m using version 3.6.5 of Python.

Follows the code:

import collections 
salario_experiencia = [(83000,8.7), (88000,8.1),
                        (48000,0.7),(76000,6),
                        (69000,6.5),(76000, 7.5),
                        (60000,2.5), (83000,10),
                        (48000,1.9),(63000,4.2)]

def tenure_bucket(experiencia):
     if experiencia < 2:
        return "Menos que 2 anos"
    elif experiencia < 5:
        return "Entre dois e 5 anos"
    else:
        return "Mais que 5 anos"

salary_by_tenure_bucket = collections.defaultdict(list)

for salario, experiencia in salario_experiencia:
    bucket = tenure_bucket(experiencia)  
    salary_by_tenure_bucket[bucket].append(salario)
    #print (salary_by_tenure_bucket) 
media_salario = {
    tenure_bucket : sum(salario)/len(salario)
    for tenure_bucket, salarios in salary_by_tenure_bucket.iteritems()
}

1 answer

2


Are two problems:

  1. In the Python 3 no longer exists iteritems(), being replaced by items().

  2. When calculating:

    sum(salario)/len(salario)
    

You are using the variable salario, which was used a few lines above to receive the salary amount. Therefore, at this point in the code this variable contains a number. And when calling sum and len with a number, make a mistake.

What you want is to use the variable salarios (plural), which you created within your Dict comprehension:

media_salario = {
    tenure_bucket: sum(salarios) / len(salarios) # use "salarios" em vez de "salario"
    for tenure_bucket, salarios in salary_by_tenure_bucket.items() # use "items" em vez de "iteritems"
}

Notice that you do for tenure_bucket, salarios, that is, the variable salarios (plural) is what should be used. The variable salario (singular) was used in loop for previous, but has no use in this excerpt.

  • That’s exactly what it was. Problem solved! media_salario = {&#xA;tenure_bucket : sum(salarios)/len(salarios)&#xA;for tenure_bucket, salarios in salary_by_tenure_bucket.items()} Output: {'Mais que 5 anos': 79166.66666666667, 'Menos que 2 anos': 48000.0, 'Entre dois e 5 anos': 61500.0}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.