0

我有一个

     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 或更高版本。

4

2 回答 2

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')
于 2012-10-28T17:04:46.120 回答
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)
于 2012-10-28T18:55:48.587 回答