【问题标题】:how to dictionary format to file? [closed]如何将字典格式转换为文件? [关闭]
【发布时间】:2012-10-28 16:52:56
【问题描述】:

我有一个

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

【问题讨论】:

  • 对于相反的我在我的钥匙周围得到''..

标签: python dictionary formatting output


【解决方案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')

【讨论】:

    【解决方案2】:

    我相信这可以满足您的所有要求。如果您删除或注释掉指示的行,它应该可以与 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)
    

    【讨论】:

    • 感谢您的时间和努力。后续问题:
    • f.write("{}{:^20}\n".format(x,str(reverse[x]).strip("[]"))) 我尝试添加宽度但它不适用于 {:^20}
    • @user1753878:我不知道——从语法上看,这个语句看起来不错。仅仅说“它不起作用”不足以让我为您提供额外的信息或建议。需要确切知道出了什么问题和/或产生了哪些错误消息。
    猜你喜欢
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 2021-08-21
    • 2021-09-20
    相关资源
    最近更新 更多