Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在字典内创建字典,在字典内';n';时代_Python_Loops_Dictionary_Nested_Iteration - Fatal编程技术网

Python 如何在字典内创建字典,在字典内';n';时代

Python 如何在字典内创建字典,在字典内';n';时代,python,loops,dictionary,nested,iteration,Python,Loops,Dictionary,Nested,Iteration,我需要一种创建n维字典的方法 基本上,每个字典包含4个键,值为1或2 我需要创建一个字典来检查它是1还是2。在这本新创建的词典中,再次“n”次。这是基本代码: dic1 = {'a': 1, 'b': 2, 'c': 1, 'd': 1} dic2 = {'a': 1, 'b': 2, 'c': 1, 'd': 2} dic0 = {'a': 2} def doing_it(dic): new_mod = {} for keys in dic: if dic[k

我需要一种创建n维字典的方法

基本上,每个字典包含4个键,值为1或2

我需要创建一个字典来检查它是1还是2。在这本新创建的词典中,再次“n”次。这是基本代码:

dic1 = {'a': 1, 'b': 2, 'c': 1, 'd': 1}
dic2 = {'a': 1, 'b': 2, 'c': 1, 'd': 2}
dic0 = {'a': 2}

def doing_it(dic):
    new_mod = {}
    for keys in dic:
        if dic[keys] == 1:
            new_mod[keys] = dic1
        if dic[keys] == 2:
            new_mod[keys] = dic2
    return new_mod

doing_it(dic0)
我需要的示例:

dic1 = {'a': 1, 'b': 2, 'c': 1, 'd': 1} #default1
dic2 = {'a': 1, 'b': 2, 'c': 1, 'd': 2} #default2

dic0 = {'a': 1, 'b': 2, 'c': 1, 'd': 2} #My starting dictionary

#first iteration
dic01 = {'a': dic1, 'b': dic2, 'c': dic1, 'd': dic2}

#second iteration
dic02 = {'a': {'a': dic1, 'b': dic2, 'c': dic1, 'd': dic1}, 'b': {'a': dic1, 'b': dic2, 'c': dic1, 'd': dic2}, 'c': {'a': dic1, 'b': dic2, 'c': dic1, 'd': dic1}, 'd': {'a': dic1, 'b': dic2, 'c': dic1, 'd': dic2}}

反复执行此
doint\u it()

def doing_it(dic):
    new_mod = {}
    for i in sorted(dic.keys()):
        if dic[i] == 1:
            new_mod[i] = dic1
        elif dic[i] == 2:
            new_mod[i] = dic2
        else:
            new_mod[i] = doing_it(dic[i])
    return new_mod

有帮助吗?你能详细说明一下吗。你能用一个简单的例子来说明你需要什么吗?我自己找到了一个答案,在帖子里,以防有人问needs@inspectorG4dget这与另一篇文章不同,因为我没有空槽可以使用defaultdics,我用答案编辑了我的文章。