Search code examples
python-3.xlistdictionarydeque

Deque appending dictionary vs Deque(dictionary) in Python


Try to get my head around adding dictionary to a deque .

Take this example:

from collections import deque
graph={}
graph['key']=['value_1','value_2','value_3']
implement_first=deque()
implement_second=deque(graph['key'])
implement_first.append(graph['key'])

and If I print:

    print(implement_first)
    print(implement_first.popleft())

I get this deque([['value_1', 'value_2', 'value_3']]) and ['value_1', 'value_2', 'value_3']

and If I print:

print(implement_second)
print(implement_second.popleft())

I get this : deque(['value_1', 'value_2', 'value_3']) and value_1

So what is going on here ? why am I getting list of list for implement_first.append(graph['key']) and what is this implementation implement_second=deque(graph['key']) does?


Solution

  • The following 2 are not equivalent

    d1 = deque(x)
    
    d2 = deque()
    d2.append(x)
    

    The deque constructor takes an iterable and appends all its elements. So the following 2 would be the same

    d1 = deque(x)
    
    d2 = deque()
    for y in x:
        d2.append(y)
    

    Yours does not raise any errors because graph["key"] is a list (an iterable) which can be both turned into a deque and be an element of a deque.