我有一個txt檔案:
:Dog : Cat or Lion : Dragon
Size : 10.2 : 20.2 : 30.5
Height : 5.4 : 10.4 : 20.7
Fat % : 0.35 : 0:20 : 0:10
我想要列標簽(Dog, Cat or Lion, Dragon)作為我的外部字典。
內部字典鍵應該是 Size, Height
所以如果我運行data['Dog'] ['Size)" 10應該列印出來,并且它們內部字典中的值是字串。
我在創建內部字典鍵時遇到問題...
uj5u.com熱心網友回復:
這是如何做到的(更詳細的解釋在另一個代碼示例中):
from collections import defaultdict
filename = 'myfile.txt'
with open(filename) as file:
dct = defaultdict(dict)
# get the first line which will be the headers
_, *headers = file.readline().split(':')
# iterate over the next lines
for line in file:
# split line by ':' to extract the row name and the data
param, *data = line.split(':')
# zip together headers with the data
for animal, value in zip(headers, data):
# add the values to the dictionary
dct[animal.strip()][param.strip()] = value.strip()
dct = dict(dct)
print(dct)
您還可以csv像這樣使用內置庫:
import csv
from collections import defaultdict
file_name = 'myfile.txt'
with open(file_name, newline='') as file:
# read the data in a dictionary iterable where it represents
# each column name and its value in each row
reader = csv.DictReader(file, delimiter=':')
# create a defaultdict with the dictionary to make it easier
# to create the inner dictionaries
dct = defaultdict(dict)
# iterate over rows
for row in reader:
# simple unpacking
(_, param), *data = row.items()
# you can
# print(param, data)
# to see what it all contains but you should understand from the names
# iterate over the data and place the values in the dictionary
# usage of defaultdict here allows to immediately use keys
# for the inner dictionary
for animal, value in data:
dct[animal.strip()][param.strip()] = value.strip()
# conver the dct to a normal dictionary
dct = dict(dct)
print(dct)
uj5u.com熱心網友回復:
邏輯通常是解決編程問題中最難的部分。這是邏輯。你可以寫代碼。
data = {} # empty dict
for each line in the file
split the line by ":"
strip leading and trailing white space from each split field
if the first field is empty
store the fields into a name_array
for each subsequent field in the line
use the field as the key of a new dict entry, where the value is an empty dict
else
use the first field as the_key
for each subsequent field in the line
get the field position (index)
use the field position to extract the name from the name_array
update data[name][the_key] = subsequent field
上述一般邏輯應該為您的程式提供一個可行的解決方案,而無需使用任何外部庫/模塊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/350562.html
