Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create ordered dict from list comprehension?

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?

like image 695
Tim Avatar asked Mar 19 '15 02:03

Tim


People also ask

Can you use List Comprehension for 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.

What is the difference between List Comprehension and dict comprehension?

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 [].

What is collections OrderedDict?

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.

How ordered dict is implemented?

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.


2 Answers

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]
like image 106
thefourtheye Avatar answered Oct 30 '22 16:10

thefourtheye


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]
like image 34
Abhijit Avatar answered Oct 30 '22 15:10

Abhijit