142k views
5 votes
Modify your program from Learning Journal Unit 7 to read dictionary items from a file and write the inverted dictionary to a file. You will need to decide on the following: 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.

User Deeksy
by
2.9k points

1 Answer

2 votes

Answer:

Following are the code to this question:

import ast as a #import package ast

d1= {}#defining an empty dictionary

def invert_dictionary(d1):#defining a method invert_dictionary

i = dict()#defining variable i that hold dict method

for k in d1:#defining for loo to check dictionary value

val = d1[k]#defining val variable to holds dictionary key values

for val1 in val:#defining another for loop to hold value of dictionary and inverse it

if val1 not in i:#defining if block to check value

i[val1] = [k]#hold key value

else:#defining else block

i[val1].append(k)#add value in dictionary

return i#return inverse value

with open("dict_items.txt", "r") as data:#use open method to add a list as a file

dict_item = a.literal_eval(data.read())#defining a variable that covert item as a text string in the input file

'''covert input string into dictionary item'''

e_val = input("Please enter a value")#defining variable e_val to input value

dict_item['4']=str(e_val)#holding value in dictionary

dict_item['5']='e'#holding value in dictionary

dict_item['6']='f'#holding value in dictionary

'''Invert the dictionary value '''

invert_data =invert_dictionary(dict_item)#defining variable to holding method value

'''calculating the format of each item of inverted dictionary as a text string output file.'''

f_data = {i:str(j[0]) for i,j in inverted_data.items() }#defining f_data to hold coverted value

import json as j#import package

with open('out_put.txt', 'w') as file:#use open method to open file

file.write(j.dumps(f_data))#add value

Step-by-step explanation:

In the above-given code has four parts which can be defined as follows:

In the first part, a method invert_dictionary is defined that accepts a dictionary, and defines two for loops in which the second loop uses a conditional statement to convert the inverse form and return its value, and after inverse it use the open method to add a list as a file, and defining a variable that covert item as a text string in the input file.

In the second step, a variable e_val is declared for input value , and use the dict_item variable to holding dictionary value, and call the method and hold its value.

In the third and fourth step it calculating the format of each item of inverted dictionary as a text string output file.

User Frank Zafka
by
3.3k points