i want to read the list of the Informaton from a CSV file and converting to the Dictionary.(Python)
file=open("myfile.csv","a ")
dic=[]
while True:
name=input("enter the name of Book:")
supply=input("supply:")
price=input("price:")
codenummber=input("isbn:")
file.write("name:" name "," "supply:" supply "," "price:" price "," "isbn:" codenummber "\n")
file.seek(0)
file1=file.read().split("\n")
dic.append(file1)
inputa=input("do you want continue? y/n:")
if inputa=="n":
for i in range (len(dic)):
print(dic[i])
break
and i want to reach to this output:
['{name':'Bostan','supply':'12','price':'13000','isbn':'2200994'}, {'name':'hafez','supply':'300','price':'30000','isbn':'222200994'}
CodePudding user response:
if I run your code, I get a csv like this:
Based on this, you can use
with open("myfile.csv", "r") as file:
file1 = file.read().split("\n")[:-1]
output = [{s[0]: s[1] for elem in book.split(",") if (s := elem.split(":"))} for book in file1]
to get this as output:
[{'name': 'book1', 'supply': '15', 'price': '20', 'isbn': 'abcde'}, {'name': 'book2', 'supply': '25', 'price': '50', 'isbn': 'fghij'}]
CodePudding user response:
@bitflip i could not run your Answer i sent my code hier .where is the Problem?.
file=open("myfile.csv","a ")
book=[]
while True:
name=input("enter the name of Book:")
supply=input("supply:")
price=input("price:")
codenummber=input("isbn:")
file.write("name:" name "," "supply:" supply "," "price:" price "," "isbn:" codenummber "\n")
file.seek(0)
file1=file.read().split("\n")
book.append(file1)
inputa=input("do you want continue? y/n:")
if inputa=="n":
dic1 = [{s[0]: s[1] for i in dic.split(",") if (s := i.split(":"))} for dic in file1]
print(dic1)
break