Python调试麻烦i/0,如何获得正确的格式?

Python trouble debugging i/0, how do I get the correct format?

我正在尝试将字典制作成格式化的字符串,然后将其写入文件,但是我的整个格式似乎都不正确。我不确定如何调试,因为我所有的测试用例都有不同的文件。我能够使用 python 中的交互模式来找出我的函数实际写入文件的内容,伙计,错了!你能帮我正确格式化吗?

给定一个排序的字典,我将它创建成一个字符串。我需要 return 的功能,就像这样:

Dictionary is : {'orange':[1,3],'apple':[2]}

"apple:\t2\norange:\t1,\t3\n"

format is: Every key-value pair of the dictionary
should be output as: a string that starts with key, followed by ":", a tab, then the integers from the value list. Every integer should be followed by a "," and a tab except for the very last one, which should be followed by a newline

这是我认为可行的功能:

def format_item(key,value):
    return key+ ":\t"+",\t".join(str(x) for x in value) 

def format_dict(d):
    return sorted(format_item(key,value) for key, value in d.items())

def store(d,filename):
    with open(filename, 'w') as f: 
        f.write("\n".join(format_dict(d)))
        f.close()
    return None

我现在最后一行的制表符太多了。如何仅在 for 循环之外编辑最后一行?

前输入:

d = {'orange':[1,3],'apple':[2]}

我的函数给出:['apple:\t2'、'orange:\t1,\t3']

但应该给出:"apple:\t2\norange:\t1,\t3\n"

将换行符添加到 format_item 中的 return 语句的末尾似乎会产生正确的输出。

return key+ ":\t"+",\t".join(str(x) for x in value) + '\n'

In [10]: format_dict(d)
Out[10]: ['apple:\t2\n', 'orange:\t1,\t3\n']