Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Programming Assignment Unit 8

Explanation:

 First, we need to open the original text file and open it. To do that, we use the command

read(). Our original dictionary is called original_dictionary.txt We also need to read its

contents and print It on the screen.

 The second step is to create a dictionary so we can store the contents of the file inside this

dictionary. For that we need an empty dictionary. So, I have created an empty dictionary

called original dictionary.

 To get the key and value for the dictionary I have split it by the newline character. I have

created a loop that iterates through the lines, it splits a single line in two parts, first part is

the key and second one the value. In dictionary every key is separated from its value by a

colon (Tutorialspoint, n.d.). Therefore, I have separated them by colon. Moreover, I have

also removed any whitespaces before and after the key or the value so get a clean look

and code. To remove trailing and leading whitespaces, we can use the .strip method in

Python (Nehme, 2024).

 Moreover, I have added the key and value inside the empty dictionary that I created

earlier.

 The next step is to create another empty dictionary to store our inverted dictionary when

our program is done. So, I have created an empty dictionary called inverted_dictionary.

 I have created another loop that iterates in the original dictionary, It checks if the values

and pair exists in the inverted dictionary. If it does exist then it appends the key to the list

of values for the that key. Moreover, if it does not exist then it creates a new pair of a

value of key-pair, however, this time key is used as the value and the value as the key.
 At this stage, I have created a new text file to store our result. It is called

inverted_dictionary and with the help of loop our data will get stored inside this text file.

 Lastly, I have read and opened the inverted_dictionary file, read its contents just to

display it on the screen.

Source Code:

Output:
References:

Tutorialspoint (n.d.). Python - Dictionary. Retrieved March 28, 2024, from

https://www.tutorialspoint.com/python_data_structure/python_dictionary_data_structure.

htm#:~:text=In%20Dictionary%20each%20key%20is,braces%2C%20like%20this

%20%E2%88%92%20%7B%7D.

Nehme, A. (2024, January). How to Trim a String in Python: Three Different Methods.

Datacamp. Retrieved March 28, 2024, from https://www.datacamp.com/tutorial/python-

trim

You might also like