create ordered dict from list comprehension?

后端 未结 2 941
孤城傲影
孤城傲影 2021-02-20 12:19

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 or

相关标签:
2条回答
  • 2021-02-20 13:01

    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]
    
    0 讨论(0)
  • 2021-02-20 13:05

    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]
    
    0 讨论(0)
提交回复
热议问题