Here is a list comprehension:
L = [{k: d[k](v) for (k, v) in l.iteritems()} for l in L]
where
L
is a list of ordered dictionaries (i.e. objects of collections.OrderedDict), where the dictionaries have the same set of keys.
d
is another ordered dictionary, which also has the same set of keys as the previous ordered dictionaries.
For each key
, d[key]
is a function which can apply to L[i][key]
, i.e. d[key](L[i][key])
.
All the given dictionaries are ordered dicts, and have the same order in their keys.
But the code will create an unordered dictionary. How can I create an ordered dict in the same key order as the given ordered dictionaries?
Method 1: Using dict() methodUsing dict() method we can convert list comprehension to the dictionary. Here we will pass the list_comprehension like a list of tuple values such that the first value act as a key in the dictionary and the second value act as the value in the dictionary.
Dictionary Comprehensions. Like a List Comprehension is a way to create a list quickly, Dictionary Comprehension is a different way of rapidly creating a Dictionary with Python. Dictionary Comprehensions have the following signature. They look a lot like List Comprehensions but use braces {} instead of brackets [].
An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Example.
Implementing an Ordered DictionaryIt starts with an inner class for representing a key-value pair. The class stores the (key, value) pairs in an array, and also maintains a dict for fast lookup of the keys. The array serves to store the order in which the items were inserted.
collections.OrderedDict
is nothing but a dict, which remembers the order in which the elements are included in it. So you can create one with its constructor like this
[OrderedDict((k, d[k](v)) for (k, v) in l.iteritems()) for l in L]
Python dictionary unlike C++ dictionary are unordered because it uses hash for its keys. Analternative would be to use an ordered specialization of python dictionary called collections.OrdredDict.
This would turn your declaration as
from collections import OrderedDict
L = [OrderedDict((k, d[k](v)) for (k, v) in l.iteritems()) for l in L]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With