In: Computer Science
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 convert 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.
------------------------------------------------------------------------------------------------------------------
The Unit 7 program:
Dr_Appointments = {'Mom':[2, 'April', 2020], 'Brother':[6, 'July', 2020], 'Sister':[6, 'January', 2021], }
def invert_dict(d):
inverse = dict()
for key in d:
val = d[key]
for val in val:
if val not in inverse:
inverse[val] =
[key]
else:
inverse[val].append(key)
return inverse
print('Dr. Appointments:', Dr_Appointments)
print('Inverted Dr. Appointments:')
Invert_Appointments = invert_dict(Dr_Appointments)
print(Invert_Appointments)
This is the expanded dictionary: the Unit 7 plus three more:
Mom: 2, April, 2020,
Brother: 6, July, 2020,
Sister: 6, January, 2021,
Aunt: 2, December, 2021,
Uncle: 6, November, 2021,
Niece: 2, December, 2020
ANSWER:
I have provided the properly commented
and indented code so you can easily copy the code as well as check
for correct indentation.
I have provided the output image of the code so you can easily
cross-check for the correct output of the code.
Have a nice and healthy day!!
CODE
# inverting dict
def invert_dict(d):
# defining empty dict
inverse = dict()
# looping through each key value of dict
for key in d:
val = d[key]
# converting val list to tuple to use it as key
val = tuple(val)
if val not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
# returning inverse
return inverse
# first reading file and storing content in as dictonary in variable
# opening file
file = open("f1.txt",'r')
# now reading content of file
content = file.read()
# loading content in dictonary format using eval funtion of python
data = eval(content)
# inverting data
inv_data = invert_dict(data)
# converting inv_data to string
string_inv = str(inv_data)
# storing string_inv to file
file_write = open("f2.txt",'w')
# writing to file_write
file_write.write(string_inv)
# file object to close
file_write.close()
INPUT IMAGE (f1.txt)
OUTPUT IMAGE
f2.txt