我有一个
d= {'fall':['basketball', 'hockey','football']
'spring': ['cross country','tennis','baseball']
'summer':['soccer', 'softball']
etc....
我想将其写入文件。如下。
秋季体育比赛:
篮球
曲棍球
足球
春季运动:
越野
网球
棒球..
到目前为止我写的代码:
for n in range(len(sp)):
print("Sports Played in",i)
print(sp[i,'\n'])
我也希望将其反转
所以它按字母顺序读取:
棒球<差距应该在这里>春天
篮球<差距应该在这里>下跌
越野<差距应该在这里>弹簧
列应排成一行。
def reverse_dict(dct):
reverse = {}
for key, vals in dct.items():
for val in vals:
if val not in reverse:
reverse[val] = []
reverse[val].append(key)
return reverse
keys=list(reverse.keys())
keys.sort()
for x in keys:
f1out.write("".join(
str([x, reverse[x]]).strip("[]").replace("[" ,'').replace(",", "'\t'")
+ '\n'))
有什么想法吗?仅限Python 3或更高版本。
答案 0 :(得分:1)
这应该这样做:
with open("data1.txt","w") as f:
for season in d:
f.write("Sports played in {0}\n".format(season))
for sp in d[season]:
f.write(sp+'\n')
答案 1 :(得分:0)
我相信这会做你要求的一切。如果你删除或注释掉指定的行,它应该适用于Python 3,但是我实际上并没有验证这是否属实。如果没有,它应该非常接近。
from __future__ import print_function # remove for Python 3
from collections import defaultdict
import sys
GAP = 4
INDENT = ' ' * 2
TEST = True # print output rather than write it to files
d = {'fall': ['basketball', 'hockey', 'football'],
'spring': ['cross country', 'tennis', 'baseball', 'archery'],
'summer': ['soccer', 'softball', 'archery'] }
def reverse_dict(dct):
reverse = defaultdict(list)
for key, vals in list(dct.items()):
for val in vals:
reverse[val].append(key)
return reverse
rev_d = reverse_dict(d)
with open("seasonal_sports.txt", "wt") as output:
if TEST: output = sys.stdout
for season in sorted(d):
print('Sports played in {}:'.format(season), file=output)
for sport in d[season]:
print(INDENT+sport, file=output)
with open("sport_seasons.txt", "wt") as output:
if TEST: output = sys.stdout
longest = max(list(map(len, rev_d)))
for sport in sorted(rev_d):
print('{:<{width}}'.format(sport, width=longest+GAP),
', '.join(rev_d[sport]), file=output)