我有一個使用字符串(編輯)作爲鍵的字典並將列表存儲爲值列表。python - 列表正在從csv作爲字符串讀入
dict = {key1: [[data1],[data2],[data3]], key2: [[data4],[data5]],...etc}
編輯:其中數據變量是從轉換後的數據幀的熊貓
實施例包含不同的數據類型的行。
df = pd.DataFrame()
df['City'] = ['New York','Austin','New Orleans','New Orleans']
df['State'] = ['NY','TX','LA','LA']
df['Latitude'] = [29.12,23.53,34.53,34.53]
df['Time'] = [1.46420e+09,1.47340e+09,1.487820e+09,1.497820e+09]
City State Latitude Time
New York NY 29.12 1.46420e+09
Austin TX 23.53 1.47340e+09
New Orleans LA 34.53 1.487820e+09
New Orleans LA 34.53 1.497820e+09
dict = {}
cities = df['City'].unique()
for c in cities:
temp = df[df['City'] == c]
dict[c] = temp.as_matrix().tolist()
#which outputs this for a given key
dict['New Orleans'] = [['New Orleans' 'LA' 34.53 1.487820e+09],
['New Orleans' 'LA' 34.53 1.497820e+09]]
我使用把它作爲一個CSV以下幾點:
reader = csv.reader(open(filename, 'r'))
dict = {}
for key,val in reader:
dict[key] = val
VAL進來尋找完美:
filename = 'storage.csv'
with open(filename,'w') as f:
w = csv.writer(f)
for key in dict.keys():
w.writerow((key,dict[key]))
我然後使用以下讀取文件回字典,除了它現在是一個字符串。例如,key1的是這樣的:
dict[key1] = "[[data1],[data2],[data3]]"
我怎樣才能在讀值列表,或從刪除引號讀入val的版本?
哪些變量'data1','data2'等?顯示[最小完整代碼](http://stackoverflow.com/help/mcve)。 –
CSV不知道Python列表是什麼。你爲什麼不使用json? – polku
假設'val'是一個表示字符串列表的字符串,那麼'd [key] = ast.literal_eval(val)'。另外,不要將您的字典命名爲'dict'。 –