1. How to format each dictionary item as a text string in the input file.
price_dict = {
'Apple': 5,
'Potato': 15,
'Tomato': 20
}
with open('dict_string', 'a+') as f:
for key, value in price_dict.items():
f.write(f'{key}:{value}\n')
2. How to covert each input string into a dictionary item
def string_to_dict():
item = input('Enter item, split key and value by ":" ').split(':')
if len(item) != 2 or not item[0] or not item[1]:
print('Enter correct data')
return string_to_dict()
dict_from_string = {item[0]: item[1]}
print(dict_from_string)
string_to_dict()
3. How to format each item of your inverted dictionary as a text string in the output file
with open('dict_string') as f:
data = dict()
for i in f.readlines():
if i != '\n':
item = i.split(':')
data[item[0]] = item[1].strip()
print(data)
4. Create an input file with your original three-or-more items and add at least three new items, for a
total of at least six items.
with open('new_input_file', 'w') as f:
f.write('Audi:1000\n'
'BMW:500\n'
'Nissan:100\n')
with open('new_input_file', 'a+') as f:
f.write('Ford:250\n'
'Chevrolet:300\n'
'Lada:2\n')
Comments
Leave a comment