简体   繁体   English

python:使用字典键的一部分作为字典值的变量

[英]python: Use part of dict key as variable for dict value

I have dictionary that looks like this: 我有这样的字典:

mapper = {
    "bigint(20)": "= Column(BigInteger)",
    "int(11)": "= Column(Integer)",
    "`": "",
    "varchar(255)": "= Column(String)",
}

I am mapping sql datatype naming into sqlalchemy-like to be replaced into a text file. 我将命名为sqlalchemy的sql数据类型映射为要替换为文本文件。 So far I am just mapping int to integer, varchar to string and so on. 到目前为止,我只是将int映射为整数,将varchar映射为字符串,依此类推。 However, my idea is to use part of the key as variable to be passed to its relative value, ie avoiding to hardcode varchar(255) and use varchar(x) to be passed to its relative value = Column(String()) having = Column(String(x)) . 但是,我的想法是使用键的一部分作为变量传递给它的相对值,即避免硬编码varchar(255)并使用varchar(x)传递给它的相对值= Column(String())具有= Column(String(x))

Something like: 就像是:

"varchar(x)": "= Column(String{})".format(x),

Do you have any suggestions how to achieve that? 您对实现该目标有什么建议吗? thanks 谢谢

A dict is a fixed set of concrete keys; dict是一组固定的具体密钥。 you cannot do what you want with a dict alone. 你不能仅凭dict就做自己想做的事。

However, you can subclass dict to provide a definition of __getitem__ that can do what you want. 但是,您可以对dict进行子类化以提供__getitem__的定义,该定义可以执行您想要的操作。 Something like 就像是

import re
class SQLDict(dict):
    def __getitem__(self, key):
        m = re.match('^varchar\((.*)\)$', key)
        if m:
            return super(SQLDict, self).__getitem__('varchar(x)') % (m.group(1),)
        else:
            return super(SQLDIct,self).__getitem__(key)

mapper = SQLDict({
    "bigint(20)": "= Column(BigInteger)",
    "int(11)": "= Column(Integer)",
    "`": "",
    "varchar(x)": "= Column(String(%s))",
})

Trying it out... 尝试一下...

>>> print mapper['varchar(15)']
'=Column(String(215))'

It's not perfect; 这并不完美; I've hard-coded varchar(x) into the definition of __getitem__ , while you might define mapper to have a key like varchar(y) instead. 我已经将varchar(x)硬编码到__getitem__的定义中,而您可能会定义mapper以使用像varchar(y)这样的键。 But this should get you started. 但这应该可以帮助您入门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM