How do you retrieve items from a dictionary in the order that they're inserted?

Is it possible to retrieve items from a Python dictionary in the order that they were inserted?


Asked by: Victoria680 | Posted: 05-10-2021






Answer 1

The standard Python dict does this by default if you're using CPython 3.6+ (or Python 3.7+ for any other implementation of Python).

On older versions of Python you can use collections.OrderedDict.

Answered by: Alina511 | Posted: 06-11-2021



Answer 2

As of Python 3.7, the standard dict preserves insertion order. From the docs:

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was implementation detail of CPython from 3.6.

So, you should be able to iterate over the dictionary normally or use popitem().

Answered by: Lenny606 | Posted: 06-11-2021



Answer 3

Use OrderedDict(), available since version 2.7

Just a matter of curiosity:

from collections import OrderedDict
a = {}
b = OrderedDict()
c = OrderedDict()

a['key1'] = 'value1'
a['key2'] = 'value2'

b['key1'] = 'value1'
b['key2'] = 'value2'

c['key2'] = 'value2'
c['key1'] = 'value1'

print a == b  # True
print a == c  # True
print b == c  # False

Answered by: Ada762 | Posted: 06-11-2021



Answer 4

The other answers are correct; it's not possible, but you could write this yourself. However, in case you're unsure how to actually implement something like this, here's a complete and working implementation that subclasses dict which I've just written and tested. (Note that the order of values passed to the constructor is undefined but will come before values passed later, and you could always just not allow ordered dicts to be initialized with values.)

class ordered_dict(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        self._order = self.keys()

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)
        if key in self._order:
            self._order.remove(key)
        self._order.append(key)

    def __delitem__(self, key):
        dict.__delitem__(self, key)
        self._order.remove(key)

    def order(self):
        return self._order[:]

    def ordered_items(self):
        return [(key,self[key]) for key in self._order]


od = ordered_dict()
od["hello"] = "world"
od["goodbye"] = "cruel world"
print od.order()            # prints ['hello', 'goodbye']

del od["hello"]
od["monty"] = "python"
print od.order()            # prints ['goodbye', 'monty']

od["hello"] = "kitty"
print od.order()            # prints ['goodbye', 'monty', 'hello']

print od.ordered_items()
# prints [('goodbye','cruel world'), ('monty','python'), ('hello','kitty')]

Answered by: Daryl584 | Posted: 06-11-2021



Answer 5

You can't do this with the base dict class -- it's ordered by hash. You could build your own dictionary that is really a list of key,value pairs or somesuch, which would be ordered.

Answered by: Michelle613 | Posted: 06-11-2021



Answer 6

Or, just make the key a tuple with time.now() as the first field in the tuple.

Then you can retrieve the keys with dictname.keys(), sort, and voila!

Gerry

Answered by: Max446 | Posted: 06-11-2021



Answer 7

I've used StableDict before with good success.

http://pypi.python.org/pypi/StableDict/0.2

Answered by: Carina346 | Posted: 06-11-2021



Answer 8

Or use any of the implementations for the PEP-372 described here, like the odict module from the pythonutils.

I successfully used the pocoo.org implementation, it is as easy as replacing your

my_dict={}
my_dict["foo"]="bar"

with

my_dict=odict.odict()
my_dict["foo"]="bar"

and require just this file

Answered by: Steven254 | Posted: 06-11-2021



Answer 9

It's not possible unless you store the keys in a separate list for referencing later.

Answered by: Miller480 | Posted: 06-11-2021



Answer 10

if you don't need the dict functionality, and only need to return tuples in the order you've inserted them, wouldn't a queue work better?

Answered by: Ryan376 | Posted: 06-11-2021



Answer 11

What you can do is insert the values with a key representing the order inputted, and then call sorted() on the items.

>>> obj = {}
>>> obj[1] = 'Bob'
>>> obj[2] = 'Sally'
>>> obj[3] = 'Joe'
>>> for k, v in sorted(obj.items()):
...     print v
... 
Bob
Sally
Joe
>>> 

Answered by: Ryan484 | Posted: 06-11-2021



Similar questions

sorting - In Python, how can you easily retrieve sorted items from a dictionary?

Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key? For example, you had this: d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}


How to retrieve a single item from nested dictionary in python

I am reading from a file with data like this: {"day" :"Monday", "alarm":"on", "kids":"School" , "work":"days"} {"day" :"Tuesday", "alarm":"on", "kids":"School" , "work":"days"} {"day" :"Wednesday", "alarm":"on", "kids":"School" , "work":"days"} {"day" :"Thursday", "alarm":"on", "kids":"School" , "work":"nights"} {"day" :"Friday", "alarm":"on", "kids":"School" , "work":"nights"} {"day" :"Saturday", "alarm":"...


sorting - Python: retrieve dictionary keys in order as added?

In Python, is there a way to retrieve the list of keys in the order in that the items were added? String.compareMethods = {'equals': String.equals, 'contains': String.contains, 'startswith': String.startswith, 'endswith': String.endswith} The keys you see here are meant for a select (dropdown) box so the order is im...


Python - retrieve info from dictionary list & syntax error

I'm trying to figure out a 'simple' dictionary/database with Python, which will retrieve a name from a list of ten, with the requested information. i.e. input is 'John phone'; output is 'John's phone number is 0401'. Apart from being completely stuck on this retrieval of specific information, python has suddenly been giving me a syntax error on the name = raw_input line. The following is the file i've sa...


python - How to retrieve a variable from a list located in a dictionary, located in a list? two


python - Retrieve first row of csv using dictionary

I am reading a csv file using the csv.DictReader class. I read on the python documentation that class csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds) If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames. I tried to get the first row of my csv file using the keys() method of...


python - How to retrieve values from nested dictionary given list of keys?

This question already has answers here:


how to store set of images in a dictionary, and retrieve it using python opencv

i have a dictionary, where i have taken the images as value and indexes as key, i have stored it using zip function, and when am trying to retrieve it, its not displaying the images. what i have done is: pth = 'D:\6th sem\Major project\Code' resizedlist = dict() for infile in glob.glob(os.path.join(path,'*.jpg')): imge = cv2.imread(infile) re_img = cv2.resize(imge,(256,256)) ImEdges = cv2.imwrite('...


python - How do I retrieve more than one item pair from a dictionary

Does anyone know how I retrieve two pairs from a dictionary I'm trying to present data in a more compact format a = {1:'item 1', 2:'item 2', 3:'item 3', 4:'item 4' } for i,j,k,l in a: print i, ' - ' ,j , ' , ' ,k, ' - ' ,l 1 - item 1 , 2 - item 2 3 - item 3 , 4 - item 4 edit - sorry ment it to look like above


python - Is there any way to retrieve data from dictionary with a tuple?

Say there is a dictionary and a tuple, I want use the tuple as keys to retrieve values from the dictionary, and then put the result into another tuple. For example, the dictionary and the tuple are below dic = {"b": "bad", "a": "alpha", "c": "change"} tup = ("a", "b", "c"), and what I want is another tuple: ("alpha", "bad", "change"), is there any appro...


sorting - In Python, how can you easily retrieve sorted items from a dictionary?

Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key? For example, you had this: d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}


Python dictionary from an object's fields

Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: >>> class Foo: ... bar = 'hello' ... baz = 'world' ... >>> f = Foo() >>> props(f) { 'bar' : 'hello', 'baz' : 'world' } NOTE: It should not include methods. Only fields.


python - How can I make a dictionary from separate lists of keys and values?

I want to combine these: keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] Into a single dictionary: {'name': 'Monty', 'age': 42, 'food': 'spam'}


python - Dictionary or If statements, Jython

I am writing a script at the moment that will grab certain information from HTML using dom4j. Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below: if type == 'extractTitle': extractTitle(dom) if type == 'extractMetaTags': extractMetaTags(dom)


Is a Python dictionary an example of a hash table?

One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?


python - Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?

The list sort() method is a modifier function that returns None. So if I want to iterate through all of the keys in a dictionary I cannot do: for k in somedictionary.keys().sort(): dosomething() Instead, I must: keys = somedictionary.keys() keys.sort() for k in keys: dosomething() Is there a pretty way to iterate t...


python - Interface to versioned dictionary

I have an versioned document store which I want to access through an dict like interface. Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int). from UserDict import DictMixin class VDict(DictMixin): def __getitem__(self, key): if isinstance(key, tuple): docid, rev = key e...


python - List all words in a dictionary that start with <user input>

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! Edit: I'm using python, but I assume that this is a fairly language-independent problem.


python - Check if a given key already exists in a dictionary and increment it

How do I find out if a key in a dictionary has already been set to a non-None value? I want to increment the value if there's already one there, or set it to 1 otherwise: my_dict = {} if my_dict[key] is not None: my_dict[key] = 1 else: my_dict[key] += 1


Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?

I have a list of variable names, like this: ['foo', 'bar', 'baz'] (I originally asked how I convert a list of variables. See Greg Hewgill's answer below.) How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values of the variables? {'foo': foo, 'bar': bar, 'baz': baz} Now that I'm re-aski...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top