I used following code to write a dictionary to a csv file.
with open('dict.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
for key, value in dict.items():
writer.writerow([key, value])
In "dict.csv" file:
accord [16, 32, 49]
according [8, 37, 49, 50]
accordingly [8, 37, 50]
account [8, 10, 16, 19, 20, 23, 25, 33, 34, 47]
where accord, according, accordingly and account are the keys and [16, 32, 49], [8, 37, 49, 50], [8, 37, 50], [8, 10, 16, 19, 20, 23, 25, 33, 34, 47] are theri values respectively.
Example:
dict={'accord':[16, 32, 49]}
Now I want to read it back to dict. How To do that?
with open('dict.csv','r') as csv_file:
reader = csv.reader(csv_file)
dict ={rows[0]:rows[1] for rows in reader}
I tried using this code but it's giving index error.
IndexError: list index out of range.
and then I use the following code which is giving me this error.
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x97 in position 5: invalid start byte.
dict={}
csv_file=pd.read_csv('dict.csv')
for index, row in csv_file.iterrows():
dict[row[0]]= row[[1]].tolist()
You essentially created a self-desinged csv format. You can read your input back in using string manipulation:
with open('dict.csv', 'w', newline="") as csv_file:
csv_file.write("""accord [16, 32, 49]
according [8, 37, 49, 50]
accordingly [8, 37, 50]
account [8, 10, 16, 19, 20, 23, 25, 33, 34, 47]""")
data = {}
with open('dict.csv', 'r') as csv_file:
for line in csv_file:
key, *values = line.replace("[","").replace("]","").replace(",","").split()
try:
data[key] = list(map(int,values)) # try to convert to int list
except ValueError:
data[key] = values # else use string list
print(data)
Output:
{'accord': [16, 32, 49],
'according': [8, 37, 49, 50],
'accordingly': [8, 37, 50],
'account': [8, 10, 16, 19, 20, 23, 25, 33, 34, 47]}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.