Answer to Question #101042 in Python for Bella

Question #101042
How to format each dictionary item as a text string in the input file.
How to covert each input string into a dictionary item.
How to format each item of your inverted dictionary as a text string in the output file.
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.
Include the following in your Learning Journal submission:
The input file for your original dictionary (with at least six items).
The Python program to read from a file, invert the dictionary, and write to a different file.
The output file for your inverted dictionary.
A description of how you chose to encode the original dictionary and the inverted dictionary in
text files
1
Expert's answer
2020-01-09T06:25:47-0500

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')


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS