create ordered dict from list comprehension?

后端 未结 2 926
孤城傲影
孤城傲影 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]
    

提交回复
热议问题