![](/img/trans.png)
[英]How to create Python dictionary with multiple 'lists' for each key by reading from .txt file?
[英]insert multiple lists from a TXT file into to dictionary?, python
我有一個行數未知的 TXT 文件。 我設法提取到列表中並且我有這個代碼。
dict_items = {"songs": [], "name": [], "length": []}
a = ["Madonna","song_name_1", "3:12"]
b = ["U2","song_name_2","3:14"]
c = ["Prince","song_name_3","4:23"]
我想通過所有 13 行 go 並將它們放入字典中,這樣:
{'songs': ['Madonna', 'U2', 'Prince'], 'name': ['song_name_1', 'song_name_2', 'song_name_3'], 'length': ['3:12', '3:14', '4:23']}
我對此感到非常困惑,有人知道如何解決這個問題嗎?
如果在文本文件的每一行中,項目用逗號分隔。 您可以使用 pandas read_csv function 讀取它,然后使用to_dict dataframe 方法將其轉換為dict。
>>> import pandas as pd
>>> def strip(s: str) -> str:
try:
return s.strip()
except Exception as e:
print(e.message)
return s
>>> df = pd.read_csv('my_text_file.txt', names=['songs', 'name', 'length'],
converters={'name': strip, 'songs': strip, 'length':strip})
>>> my_dict = df.to_dict(orient='list')
>>> print(my_dict)
{'songs': ['Madonna', 'U2', 'Prince'], 'name': ['song_name_1', 'song_name_2', 'song_name_3'], 'length': ['3:12', '3:14', '4:23']}
文本文件內容在哪里
Madonna, song_name_1, 3:12
U2, song_name_2, 3:14
Prince, song_name_3, 4:23
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.