使用单个函数编辑多个词典:

时间:2012-11-30 00:01:54

标签: python dictionary

假设我有3个空字典:

dic1 = {}
dic2 = {}
dic3 = {}

我想使用一个函数一次性添加这些词典。到目前为止,最简单的方法是:

def fillDics(x):
    count = 0
    for i in range(0, x):
            if count==0:
                    dic1[legendaryfn[count]] = 0
                    dic1[legendary[count]] = 1
                    count+=1

            if count==1:
                    dic2[legendaryfn[count]] = 0
                    dic2[legendary[count]] = 1
                    count+=1

等等,这看起来非常低效。我错过了什么?我对编程很陌生,所以我很感激您提供的任何帮助。

2 个答案:

答案 0 :(得分:0)

这就是这样完成的。

for myDict in [dict1, dict1, dict3]:
  myDict[key] = value

此外,如果数值对您有意义,您可以添加枚举:

for idx, myDict in enumerate([dict1, dict2, dict3]):
  myDict['position'] = idx

或者你有什么。

答案 1 :(得分:0)

您可以使用词典列表

def fillDics(x):
    for d in [dict1,dict2,dict3]:
        d[legendaryfn[count]] = 0
        d[legendary[count]] = 1