![](/img/trans.png)
[英]Get the dictionary from elements in the list of a column where key-value pair are number of elements and element value in pandas
[英]for loop to get the elements in key value pair
我試圖從 csv 文件中讀取數據,並希望將其存儲在鍵值對中。
我嘗試的代碼如下:
csv_data = []
with open('/Users/tejas/textTocsv/pair.csv') as paircsv:
reader = csv.DictReader(paircsv, delimiter = ',' )
for row in reader:
#im stucked over here
對.csv數據
id ppid
1 22rt3
12 3456r4
23 w232w
我希望數據位於鍵值對中,以便我可以在程序中進一步使用它。 先感謝您。
您走在正確的軌道上,但是正如@Heike 指出的那樣,考慮到您的數據結構,您最好使用csv.reader
而不是csv.DictReader
。 這是一個示例,說明如何從 csv 文件開始,並以字典結尾,以供以后在程序中使用。
例子:
from io import StringIO
import csv
# Simplified the example using StringIO instead of file I/O.
# Note: replaced spaces with commas as delimeters
paircsv = StringIO("""id,ppid
1,22rt3
12,3456r4
23,w232w
""")
# Commenting this out for StringIO example
# with open('/Users/tejas/textTocsv/pair.csv') as paircsv:
reader = csv.reader(paircsv, delimiter = ',' )
# Construct a dictionary from the key, value pairs in the CSV file
csv_data = {
key: value
for key, value in reader
}
print(my_dict)
Output:
{'id': 'ppid', '1': '22rt3', '12': '3456r4', '23': 'w232w'}
存儲在字典中的簡單示例
import csv
csv_data={}
with open("/Users/tejas/textTocsv/pair.csv") as paircsv:
reader =csv.reader(paircsv)
for key,value in reader:
csv_data[key]=value
print(csv_data)
輸出
{'id': 'ppid', '1': '22rt3', '12': '3456r4', '23': 'w232w'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.