English 中文(简体)
超越{......} 通知,从而获得命令分局,而不是法令?
原标题:Override the {...} notation so i get an OrderedDict() instead of a dict()?

最新信息:为3.7+3 保证维持插入令的法令

I want to use a .py file like a config file. So using the {...} notation I can create a dictionary using strings as keys but the definition order is lost in a standard python dictionary.

我的问题:是否可能凌驾于{......}的否决,以便我拿到OrderedDict(),而不是一个dict(<>>?

我希望,简单地凌驾于命令的构造者之上(dict = OrderedDict)。 工作会奏效,但却没有工作。

例如:

dict = OrderedDict
dictname = {
    B key :  value1 ,
    A key :  value2 ,
    C key :  value3 
   }

print dictname.items()

产出:

[( B key ,  value1 ), ( A key ,  value2 ), ( C key ,  value3 )]
最佳回答

这里有一个几乎给你希望的同yn:

class _OrderedDictMaker(object):
    def __getitem__(self, keys):
        if not isinstance(keys, tuple):
            keys = (keys,)
        assert all(isinstance(key, slice) for key in keys)

        return OrderedDict([(k.start, k.stop) for k in keys])

ordereddict = _OrderedDictMaker()
from nastyhacks import ordereddict

menu = ordereddict[
   "about" : "about",
   "login" : "login",
    signup : "signup"
]

<><>Edit>: 另有一些人独立发现这一点,并出版了odictliteral 。 关于PyPI的一揽子计划,提供略微更彻底的执行——,使用该一揽子方案,而不是

问题回答

为了从字面上获取你要求的东西,你不得不用你档案的yn树dle。 我不认为这样做是可取的,但我不能抵制尝试的诱惑。 因此,我们来到这里。

首先,我们创建了一个功能为my_execfile()的模块,该模块像在execfile(>中建立,但所有词汇显示的出现,例如{3:4,“a”: 2},由以下明确电话取代:dict(<>/code>>,例如。 (当然,我们可以通过电话<代码>采集直接取而代之。) OrderedDict(,但我们不想过分侵扰。 该法典:

import ast

class DictDisplayTransformer(ast.NodeTransformer):
    def visit_Dict(self, node):
        self.generic_visit(node)
        list_node = ast.List(
            [ast.copy_location(ast.Tuple(list(x), ast.Load()), x[0])
             for x in zip(node.keys, node.values)],
            ast.Load())
        name_node = ast.Name("dict", ast.Load())
        new_node = ast.Call(ast.copy_location(name_node, node),
                            [ast.copy_location(list_node, node)],
                            [], None, None)
        return ast.copy_location(new_node, node)

def my_execfile(filename, globals=None, locals=None):
    if globals is None:
        globals = {}
    if locals is None:
        locals = globals
    node = ast.parse(open(filename).read())
    transformed = DictDisplayTransformer().visit(node)
    exec compile(transformed, filename, "exec") in globals, locals

有了这一修改,我们can<>>>>> /em>修改了字典显示器的行为,改写了<条码>。 例如:

# test.py
from collections import OrderedDict
print {3: 4, "a": 2}
dict = OrderedDict
print {3: 4, "a": 2}

现在,我们可以使用<代码>my_execfile(”test.py”管理这一档案,得出产出。

{ a : 2, 3: 4}
OrderedDict([(3, 4), ( a , 2)])

Note that for simplicity, the above code doesn t touch dictionary comprehensions, which should be transformed to generator expressions passed to the dict() constructor. You d need to add a visit_DictComp() method to the DictDisplayTransformer class. Given the above example code, this should be straight-forward.

我再说一遍,我不建议用这种语调。 页: 1 ConfigParser model?

<代码>OrderedDict is not “standard python syntax”,然而,一套定购的关键数值(按标准python syntax)只是:

[( key1 name ,  value1 ), ( key2 name ,  value2 ), ( key3 name ,  value3 )]

明确加入<代码> OrderedDict:

OrderedDict([( key1 name ,  value1 ), ( key2 name ,  value2 ), ( key3 name ,  value3 )])

另一种选择是,如果需要的话,将<编码>字标。

sorted(dictname.items())

As of python 3.6, all dictionaries will be ordered by default.

插入令始终保留在新的<条码>中。

>>>x = { a : 1,  b :2,  c :3 }
>>>list(x.keys())
[ a ,  b ,  c ]

http://docs.python.org/3.6/whatsnew/3.6.html 新的compact, 命令执行,用于执行这两项命令。

如果你所寻求的是一种容易使用先入为主的方式,则考虑设立一个子级的特许分行,并增加操作员,以更新该字典,例如:

from collections import OrderedDict

class OrderedMap(OrderedDict):
    def __add__(self,other):
        self.update(other)
        return self

d = OrderedMap()+{1:2}+{4:3}+{"key":"value"}

d 定购单([(1、2)、(4、3)、(关键、价值)]


另一种可能的yn-苏加例子,使用lic合物:

class OrderedMap(OrderedDict):
    def __getitem__(self, index):
        if isinstance(index, slice):
            self[index.start] = index.stop 
            return self
        else:
            return OrderedDict.__getitem__(self, index)

d = OrderedMap()[1:2][6:4][4:7]["a":"H"]




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...