If youve previously answered this dont post the same answer again, thanks def st
ID: 3706597 • Letter: I
Question
If youve previously answered this dont post the same answer again, thanks
def store(d,filename): Given a dictionary d and a string filename, create a new file named filename and output the content of d into that file. You can assume that the dictionary d always has the key:value format as string:[list,of,integers]. 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. Multiple items of the dictionary must be sorted asciibetically by their keys. See the example below.
o Assumptions: (1) if a file named filename already exists, then the content should be overwritten; (2) dictionary d could be empty; (3) the value list could be empty; and (4) the function returns None.
? Examples: o d = {'orange':[1,3],'apple':[2]}
o store(d,"out.txt") should end up with a file to the right # the file contents should be read as this string: # "apple: 2 orange: 1, 3 "
Explanation / Answer
def store(d, filename): with open(filename, 'w') as f: keys = sorted(d.keys()) for key in keys: f.write(key + ": ") lst = d[key] for i, num in enumerate(lst): f.write(str(num)) if i != len(lst) - 1: f.write(', ') else: f.write(' ') d = {'orange': [1, 3], 'apple': [2]} store(d, "out.txt")