Home > Net >  how to make a dictionary of inputs
how to make a dictionary of inputs

Time:12-16

these are the inputs:

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

and I tried to make dictionaries of each line separated by ":" for example name:SignalsAndSystems.

this is my code but the code makes dictionaries only from the first line of the inputs.

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)

the answer that I'm looking for is:

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

CodePudding user response:

You aren't creating a dictionary in your for loop. You need to create a dictionary, then update it with your new key value pairs, before appending it to your list.

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)
  • Related