這些是輸入:
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"}
]
uj5u.com熱心網友回復:
您沒有在 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386388.html
