說我有一個檔案是
1 hchen 50
2 vryzhikov 60
3 kmannock 74
4 vryzhikov 53
我將名稱作為鍵,將分數作為值的字典。如果某人有 2 個不同的分數,則兩個分數都會以該名稱出現。
像這樣的東西:
hchen 50
vryzhikov 53 60
kmannock 74
infile= open("students.txt", "r")
d = {}
with open("students.txt") as f:
for line in f:
a = line.split()
key = a[1]
val = a[2]
d[(key)] = val
print(d)
A = input()
print(d.get(A))
有可能得到我想要的嗎?
uj5u.com熱心網友回復:
要打開檔案并將其讀入字典,您可以使用:
out = {}
with open("students.txt", "r") as f_in:
for line in map(str.strip, f_in):
if line == "":
continue
_, key, val = line.split()
out.setdefault(key, []).append(val)
print(out)
印刷:
{"hchen": ["50"], "vryzhikov": ["60", "53"], "kmannock": ["74"]}
對于格式化列印使用:
for k, v in out.items():
print(k, *v)
印刷:
hchen 50
vryzhikov 60 53
kmannock 74
uj5u.com熱心網友回復:
您可以使用defaultdict值型別是串列的地方:
from collections import defaultdict
infile= open("students.txt", "r")
d = defaultdict(lambda: [])
with open("students.txt") as f:
for line in f:
a = line.split()
key = a[1]
val = a[2]
d[key].append(val)
print(dict(d))
這將輸出:
{'hchen': ['50'], 'vryzhikov': ['60', '53'], 'kmannock': ['74']}
uj5u.com熱心網友回復:
為了避免使用字串操作決議資料,csv可以使用標準庫中的資料。可以指定自定義列分隔符,這里使用了空格字符。
import csv
# result
res = {}
# open file
path = "students.txt"
with open(path, 'r', newline='') as fd:
# rows iterator
rows = csv.reader(fd, delimiter=" ")
# iterate through each row and skip line number
for _, name, score in rows:
if name in res:
res[name].append(score)
else:
res[name] = [score]
print(res)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528993.html
標籤:Python文件字典
上一篇:如何計算平均工資={“Ben”:“82,500”,“Bob”:“83,750”,“Mike”:“90,000”,“Ann”:“89,000”,“Sue”:“80,000”}
