Python order Dict with a pre-defined order

Python order Dict with a pre-defined order

ordered dictionary python
python sort dictionary by value descending
sort dictionary by value python 3
python sort dictionary by value then key
python sort dictionary of dictionaries by value
python ordereddict keys
python sorteddict
python dictionary insertion order

Receive a dict and return a new ordered dict

A json returned from an api:

{
    'host': '192.168.0.1',
    'name': 'my_new_name',
    'port': 443,
    'something_more': 'hello'
}

The goal:

{
    'name': 'my_new_name',
    'something_more': 'hello',
    'host': '192.168.0.1',
    'port': 443
}

there is some way where I can define the order of keys?

For example to achieve this order on goal:

key_order = ('name', 'something_more', 'host', 'port')

Thanks


If you're using Python 3.7 or later*, you can specify the order of items in your dict, because insertion order is preserved. Create a new dictionary and insert the items in whatever order you like:

def reorder_items(d, keys):
    d = d.copy() #we're going to destructively modify d, so make a copy first
    result = {}
    for key in keys:
        if key in d:
            result[key] = d.pop(key)
    #the user might not have supplied all the keys belonging to d, 
    #so insert anything we haven't touched yet
    result.update(d)
    return result

d = {
    'host': '192.168.0.1',
    'name': 'my_new_name',
    'port': 443,
    'something_more': 'hello'
}

desired_key_order = ('name', 'something_more', 'host', 'port')
goal = reorder_items(d, desired_key_order)
print(goal)

Result:

{'name': 'my_new_name', 'something_more': 'hello', 'host': '192.168.0.1', 'port': 443}

(*you can also do this in CPython 3.6, but this is an implementation detail which should not be relied upon)

Prior to 3.7, you can't directly control how items in a dict are ordered. But you can use the collections.OrderedDict type. Use the function in the previous code block, switching out result = {} with result = collections.OrderedDict().


A more concise (albeit slightly opaque) approach is:

result = {key:d[key] for category in (desired_key_order, d.keys()) for key in category if key in d}
#or, for versions prior to 3.7,
result = collections.OrderedDict((key, d[key]) for category in (desired_key_order, d.keys()) for key in category if key in d)

This takes advantage of the fact that dict comprehensions and OrderedDict can be constructed with duplicate keys, while staying in order in relation to the first appearance of each key.

This is still a little longer than jpp's solution, since it is trying to be a bit more error-tolerant. It works even if d contains keys that desired_key_order doesn't, and vice-versa. Items whose order is not specified will appear in the result after items that do have a specified order.

OrderedDict, Before Python 3.6 a regular dict did not track the insertion order, and iterating over it produced the values in order based on how the keys are  OrderedDict in Python An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. The only difference between dict() and OrderedDict() is that: OrderedDict preserves the order in which the keys are inserted.


You can use a list comprehension to feed a list of tuples to collections.OrderedDict:

from collections import OrderedDict

d = {'host': '192.168.0.1', 'name': 'my_new_name',
     'port': 443, 'something_more': 'hello'}

key_order = ('name', 'something_more', 'host', 'port')
res = OrderedDict([(k, d[k]) for k in key_order])

OrderedDict([('name', 'my_new_name'),
             ('something_more', 'hello'),
             ('host', '192.168.0.1'),
             ('port', 443)])

Works for Python 2.x onwards. For Python 3.7+, you can rely on insertion ordering and use a regular dictionary.

How to Sort Python Dictionaries by Key or Value, We can see this method has given us a list of the keys in ascending order, and in almost alphabetical order, depending on what we define as "  Ordered Dictionary in python 3 with example : Ordered Dictionary or OrderedDict is subclass of Dictionary in python . It acts similar to a dictionary, i.e. it will have all the methods than a dictionary have. Only difference is that it remembers the order how the keys are inserted to the dictionary.


Ordered Dictionary is the thing you need my friend.]

from collections import OrderedDict
d = OrderedDict([
('name', 'my_new_name'),
('something_more', 'hello'),
('host', '192.168.0.1'),
('port', 443)
])

Edit: this only works in Python 3.6+. Also feed the OrderedDict with a list of tuples instead of a dictionary to maintain the order of key-value pairs.

PEP 372 -- Adding an ordered dictionary to collections, That the ordering is preserved makes an OrderedDict useful for a couple of that allows an application to set the type of dictionary used internally. an already built dictionary so order is lost before the object hook sees it. Standard dict objects preserve order in the reference (CPython) implementations of Python 3.5 and 3.6, and this order-preserving property is becoming a language feature in Python 3.7. You might think that this change makes the OrderedDict class obsolete. However, there are at least two good reasons to continue using OrderedDict.


If you're on Python <3.7, OrderedDict preserves the order of the items:

from collections import OrderedDict

d = OrderedDict([
        ('name', 'my_new_name'),
        ('something_more', 'hello'),
        ('host', '192.168.0.1'),
        ('port', 443)
    ])

# OrderedDict([('name', 'my_new_name'), ('something_more', 'hello'), ('host', '192.168.0.1'), ('port', 443)])

What's New In Python 3.1, The standard library now supports use of ordered dictionaries in several modules​. Since an ordered dictionary remembers its insertion order, it can be used in conjuction with Previously it returned a float: The new I/O library (as defined in PEP 3116) was mostly written in Python and quickly proved to  Using a Lambda to Order the Output in Alphabetical Order First, note that we're going to use sorted. This will sort everything between the () in ascending order. Run help ages.items () is called to break the ages dict up into the five individual items. Note that these "items" I'm referring We


Sorting HOW TO, Another difference is that the list.sort() method is only defined for lists. key parameter to specify a function to be called on each list element prior the ordering of the decorated tuples will be determined by at most the For instance, if the student grades are stored in a dictionary, they can be used to sort a  As of Python 3.6 the built-in dict will be ordered. Good news, so the OP's original use case of mapping pairs retrieved from a database with unique string ids as keys and numeric values as values into a built-in Python v3.6+ dict, should now respect the insert order. If say the resulting two column table expressions from a database query like:


Python : How to Sort a Dictionary by key or Value ? – thispointer.com, It will print the dictionary in a sorted order of keys i.e. an argument and calls it on each element prior to make comparison with other elements. Sorting Python dictionaries by Keys. If we want to order or sort the dictionary objects by their keys, the simplest way to do so is by Python's built-in sorted method, which will take any iterable and return a list of the values which has been sorted (in ascending order by default).


16.4. Sorting a Dictionary, Previously, you have used a dictionary to accumulate counts, such as the The dictionary's keys are not sorted in any particular order. In fact The other meaning is the parameter name for the function that you pass into the sorted function. OrderedDict is a subclass of the dictionary, which maintains the order in which the elements/items are added to it. OrderedDict preserves the order of insertion of the elements. A default dict does not save the order and results in the iteration in an arbitrary order.