Python Requests set cookies in a non-random order
Question: I need to send cookies in a specific, not random order.

Python requests use a dictionary to manage cookies, so the predefined cookies
I set are always in a random order.

Also, the subsequent cookies from the session are placed randomly after the
predefined cookies.

    
    
    import requests
    
    s = requests.Session()
    
    predefined_cookies = dict(cookie1='a', cookie2='b', cookie3='c')
    r = s.get('http://eu.httpbin.org/cookies/set?k1=v1&k2=v2', cookies=predefined_cookies)
    r = s.get('http://eu.httpbin.org/cookies/set?k3=v3&k4=v4', cookies=predefined_cookies)
    

Outcome:

    
    
    cookie2=b; cookie1=a; cookie3=c; k2=v2; k1=v1
    cookie2=b; cookie1=a; cookie3=c; k3=v3; k2=v2; k4=v4; k1=v1
    

Ideally, I'd like to send the predefined cookies in an order they're written,
but more importantly, I need to place a session cookie I want at a very end,
so for example place a k4=v4 cookie at the very end.

This doesn't have to be a session. I'd appreciate your input.

  * [cookies documentation](http://docs.python-requests.org/en/latest/api/#cookies)
  * [headers dict ordering](http://stackoverflow.com/a/29474948/4674587)


Answer: You can use
[`OrderedDict`](https://docs.python.org/2/library/collections.html#collections.OrderedDict),
from the [`collections`
module](https://docs.python.org/2/library/collections.html), to keep your data
in the order it was inserted.

    
    
    >>> import collections
    >>> d = collections.OrderedDict()
    >>> d["cookie1"] = 'a'
    >>> d["cookie2"] = 'b'
    >>> d["cookie3"] = 'c'
    

You can check to see the data is in the right place:

    
    
    >>> print(d)
    OrderedDict([('cookie1', 'a'), ('cookie2', 'b'), ('cookie3', 'c')])
    

