【问题标题】:how to make a dictionary of inputs如何制作输入字典
【发布时间】:2021-12-16 05:43:13
【问题描述】:

这些是输入:

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"}
]

【问题讨论】:

    标签: python dictionary input


    【解决方案1】:

    您没有在 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 2018-09-26
      • 2014-09-10
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      相关资源
      最近更新 更多