Search code examples
pythondeque

Dictionary key and deque, dont work second popleft or first pop. python


I am a begginer in python, i have a dictionary that has the key name and value as a deque, when i add in my deque it works, but when i try to withdraw with popleft only the first one works

from collections import deque

class EmployeePoint:

    dic = {}

    def __init__(self,name,point):

        self.name = name
        self.point = point


people1 = EmployeePoint("Rafael","18")
people2 = EmployeePoint("Rafael","19")
people3 = EmployeePoint("Rafael","20")

EmployeePoint.dic["Rafael"] = deque([people1])
EmployeePoint.dic["Rafael"].append([people2])
EmployeePoint.dic["Rafael"].append([people3])


print EmployeePoint.dic["Rafael"].popleft().point
print EmployeePoint.dic["Rafael"].popleft().point

Track back:

18 Traceback (most recent call last): File "main.py", line 23, in print EmployeePoint.dic["Rafael"].popleft().point AttributeError: 'list' object has no attribute 'point'


Solution

  • Initializing the deque is fine with deque([people1]) but you shouldn't be appending a list with one item in it (i.e. [people2] instead .append(people2)

    from collections import deque
    
    class EmployeePoint:
    
        dic = {}
    
        def __init__(self,name,point):
    
            self.name = name
            self.point = point
    
    
    people1 = EmployeePoint("Rafael","18")
    people2 = EmployeePoint("Rafael","19")
    people3 = EmployeePoint("Rafael","20")
    
    EmployeePoint.dic["Rafael"] = deque([people1])
    EmployeePoint.dic["Rafael"].append(people2)
    EmployeePoint.dic["Rafael"].append(people3)
    
    
    print (EmployeePoint.dic["Rafael"].popleft().point)
    print (EmployeePoint.dic["Rafael"].popleft().point) 
    # py3 print paretheses 
    

    Output:

    18

    19