二维数组在python中给出不正确的结果

时间:2014-07-23 11:26:08

标签: python arrays

我有这个代码通过循环

创建2d数组
result = dict()
final = dict()

with open(self.json_file , 'w') as outfile:
    for entry in sections_list:
        path_items = raw_config.items(entry)
        for key,path in path_items:
            final[key]=path
            result[entry] = final
    json.dump(result, outfile)

但结果我得到了每个条目的所有关键,路径! 该怎么办 ???

1 个答案:

答案 0 :(得分:2)

从你的代码中,我认为你想要一个包含dict元素的dict,你可以这样做:

result = dict()
with open(self.json_file , 'w') as outfile:
    for entry in sections_list:
        path_items = raw_config.items(entry)
        result[entry] = dict()
        for key,path in path_items:
            result[entry][key] = path

    json.dump(result, outfile)

如果path_items是包含两个元素的list / tuple的列表/元组,则可以使代码更简单:

result = dict()
with open(self.json_file , 'w') as outfile:
    for entry in sections_list:
        path_items = raw_config.items(entry)
        result[entry] = dict(path_items)

    json.dump(result, outfile)