Python如何从名称和反向生成dicts

时间:2013-05-17 05:45:27

标签: python dictionary code-generation generator

我想简化我的代码,特别是避免使用方括号;所以我的问题是:

def someFunction():
    someString = "Hi!"
    someNumber = 22
    somePointer = ""
    someList = []

    names_list = ['someString','someNumber','somePointer','someList']
    val_list = [someString, someNumber, somePointer, someList]

    someDict = {}

    for i in range( len( names_list ) ) :
        someDict[names_list[i]] = val_list[i]  

    someOtherFunction( someDict )

def someOtherFunction( dict ):
    for key, value in dict.iteritems() :
        print key, value

    print someString, someNumber

someFunction()

是否可以这样做?

3 个答案:

答案 0 :(得分:1)

如果我理解正确,你想要一个将变量名与值相关联的字典。我建议您构建一个包含名称的列表和一个包含值的列表。然后,您将项目附加到您的词典。

someString = "Hi!"
someNumber = 22
somePointer = 4
someList = []

names_list = ['someString','someNumber','somePointer','someList']
val_list = [someString, someNumber, somePointer, someList]
len_list = len(val_list)

someDict = {}

for i in range(len_list) :
    someDict[names_list[i]] = val_list[i]  

然后,你可以查询你的dict,比如说

>>> someDict['someString']
'Hi!'

答案 1 :(得分:1)

无法理解为什么这会有用 如果您知道变量列表,它们将用于某些函数

# generate names and values again at other place
def foo():
    for d in someDict :
        d_name = d

然后你无法在函数调用期间解压缩它们

def foo(someString=None,
        someNumber=None,
        somePointer=None,
        someList=None):
    pass

foo(**someDict)

答案 2 :(得分:0)

我找到的最简单的方法是使用构造函数构建的dict():

someString = "Hi!"
someNumber = 22
somePointer = ""
someList = []

someDict = dict( 
    string = someString, number = someNumber,
    pointer = somePointer, list = someList )

print someDict

Output : { "string" : "Hi", "number" : 22, "pointer" : "", "list" : [] }