如何制作输入字典

how to make a dictionary of inputs

这些是输入:

name:SignalsAndSystems genre:engineering author:Oppenheim
name:calculus genre:mathematics author:Thomas
name:DigitalSignalProcessing genre:engineering author:Oppenheim

我试着为每一行制作字典,用“:”分隔,例如 name:SignalsAndSystems

这是我的代码,但代码仅从输入的第一行生成字典。

lst_inps = []
for i in range(2):
    inp = input()
    inp = inp.split(" ")
    for item in inp:
        attribute, value = item.split(":")
        dict.update({attribute: value})
        lst_inps.append(dict)

我正在寻找的答案是:

[
    {"name":"SignalsAndSystems", "genre":"engineering", "author":"Oppenheim"} , 
    {"name":"calculus", "genre":"mathematics", "author":"Thomas"} , 
    {"name":"DigitalSignalProcessing", "genre":"engineering", "author":"Oppenheim"}
]

您没有在 for 循环中创建字典。您需要创建一个字典,然后用您的新键值对更新它,然后再将它添加到您的列表中。

lst_inps = []
for i in range(3):
    new_dict = dict() # create the dictionary here
    inp = input()
    inp = inp.split(" ")
    for item in inp:
        attribute, value = item.split(":")
        new_dict.update({attribute: value}) # add your key value pairs to the dictionary
    lst_inps.append(new_dict) # append your new dictionary to the list

print(lst_inps)