【问题标题】:Why does Python(3.7) keep overriding key:value pairs in my nested dictionary?为什么 Python(3.7) 在我的嵌套字典中不断覆盖键:值对?
【发布时间】:2019-06-08 23:38:25
【问题描述】:

我想先说我复制了 python 终端中的代码精神:

A = {}
A["Q"] = {}
A["Q"]["creation"] = {}
A["Q"]["creation"]["reactants_1"] = ["R1","R2"]

打印 A 给出了人们期望的结果:

{"Q" : {"creation" : {"reactants_1" : ["R1","R2"]}}}

然后添加:

A["Q"]["creation"]["reactants_2"] = ["R3","R4"]

产量:

{"Q" : {"creation" : {"reactants_1" : ["R1","R2"], "reactants_2" : ["R3","R4"]}}}

但是我在下面显示了一个函数,当正确运行时,它会分配前几个键:值对,但是当它循环到 x 的第二个值时,它会用新的替换它之前编写的第一个键:值对关键不一样。

使用上面的例子我们只会得到:

{"Q" : {"creation" : {"reactants_2" : ["R3","R4"]}}}

Reactions 是一个数组,包含类似“e+e+p=e+H_1”的内容,格式如下:

["e+e+p=e+H_1", "e+e+p=e+H_2",...,"e+H_10=e+e+p"]

Species 是一个数组,如:

[["e", 100000],["p", 100000],...]

现在我们只关心字符串部分。

diff_input 是一个空字典开头

reactions_const 包含,对于每个反应,左侧和右侧是分开的 - 在函数的早期被视为 [x][0][0] 和 [x][0][1] 以及其他一些信息暂时不重要。

rates_names 是我以后可以使用的每个反应的唯一标识符数组,因此使用字典方法。

打印语句都是我试图弄清楚为什么它不起作用

def rate_eqns(diff_input, reactions, species, reactions_const, 
          rates_names):

for x in range(len(reactions)):
    # for each reaction
    # split the left and right hand side up into lists of their 
    # respective species involved for counting later

    print("reaction: " + str(x) + " " + str(reactions[x]))

    species_lhs = reactions_const[x][0][0].split('+')
    print("LHS = " + str(species_lhs))

    species_rhs = reactions_const[x][0][1].split('+')

    for y in range(len(species)):  
        # For each species, create a sub-dictionary
        diff_input[species[y][0]] = {}

        # create sub-dictionaries in each species for creation, destruction and preservation/neutral paths
        diff_input[species[y][0]]["destruction"] = {}
        diff_input[species[y][0]]["creation"] = {}
        diff_input[species[y][0]]["balanced"] = {}

        # check if species occurs in each reaction

        if species[y][0] in reactions[x][0]:

            # if you start with more of it than you finish its destruction
            if species_lhs.count(species[y][0]) > species_rhs.count(species[y][0]):

                # if true: add an entry to the dictionary which holds the reaction identifier
                # bound to the destruction/creation/balanced identifier bound to the species identifier.
                print("species:" + str(species[y][0]) + " found net loss from reactants")
                print("LHS = " + str(species_lhs))
                print("RHS = " + str(species_rhs))
                print("reaction designation = " + str(rates_names[x]) + " Destruction of species")
                print("-------------")
                diff_input[species[y][0]]["destruction"][rates_names[x]] = species_lhs

            elif species_lhs.count(species[y][0]) == species_rhs.count(species[y][0]):
                print("species:" + str(species[y][0]) + " found no change in number")
                print("LHS = " + str(species_lhs))
                print("RHS = " + str(species_rhs))
                print("reaction designation = " + str(rates_names[x]) + " preservation of species")
                diff_input[species[y][0]]["balanced"][rates_names[x]] = species_lhs

            elif species_lhs.count(species[y][0]) < species_rhs.count(species[y][0]):
                print("species:" + str(species[y][0]) + " found net gain from reactants")
                print("LHS = " + str(species_lhs))
                print("RHS = " + str(species_rhs))
                print("reaction designation = " + str(rates_names[x]) + " creation of species")
                diff_input[species[y][0]]["creation"][rates_names[x]] = species_lhs

        # else:
            # print(str(species[y][0]) + " not found in reaction")
        print(diff_input)
        a = input("press return to continue")
with open('diff_input.txt', 'w') as file:
    file.write(str(diff_input))

return diff_input

文件保存部分是可选的,有没有其他人遇到过用新键覆盖现有键的字典?

感谢您的耐心等待,感谢您对我的格式提出任何建议(我试图使其尽可能好,但不包括脚本的其余部分)

【问题讨论】:

    标签: python python-3.x dictionary nested overriding


    【解决方案1】:

    species[1][0] 的实际值必须恰好等于species[0][0],这样当它循环到x 的第二个值时,赋值diff_input[species[y][0]] = {} 将覆盖前一个的子字典自 species[y][0] 以来的迭代保持不变。

    为了更简单地使用您的示例代码,在您的外部循环中,您正在进行以下初始化:

    A["Q"] = {}
    A["Q"]["creation"] = {}
    

    所以即使你的内部循环为 sub-dict 分配了一些值:

    A["Q"]["creation"]["reactants_1"] = ["R1","R2"]
    

    只要"Q" 仍然是分配的主键,A["Q"] = {} 就会在下一次迭代中覆盖它。

    【讨论】:

    • 这正是问题所在。不敢相信我没有发现它!松了一口气,我不会发疯。非常感谢您这么快的回复!
    猜你喜欢
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 2020-10-01
    相关资源
    最近更新 更多