Abdul-Azeez Adeyinka UoPeople Computer Science Assignment 122
Abdul-Azeez Adeyinka UoPeople Computer Science Assignment 122
writes the inverted dictionary to another file. The program uses the following steps:
1. Open the input file in read mode and use the eval function to convert the file content into a
Python dictionary object. Assign the dictionary to a variable called original_dict.
2. Create an empty dictionary called inverted_dict to store the inverted key-value pairs.
3. Loop through each key-value pair in original_dict and check if the value is a list or a single
item. If it is a list, loop through each item in the list and add it as a key to inverted_dict with the
original key as its value. If it is a single item, add it as a key to inverted_dict with the original
key as its value.
4. Open the output file in write mode and use the str function to convert the inverted_dict into a
string. Write the string to the output file and close both files.
apple: red
banana: yellow
cherry: red
mango: yellow
}
# Python code
original_dict = eval(input_file.read())
input_file.close()
inverted_dict = {}
if isinstance(value, list):
# Add the item as a key and the original key as its value to inverted_dict
# If the item already exists as a key, append the original key to its value list
if item in inverted_dict:
inverted_dict[item].append(key)
else:
inverted_dict[item] = [key]
else:
# Add the value as a key and the original key as its value to inverted_dict
# If the value already exists as a key, append the original key to its value list
if value in inverted_dict:
inverted_dict[value].append(key)
else:
inverted_dict[value] = [key]
output_file.write(str(inverted_dict))
output_file.close()
'black': ['grapes'],
'green': ['grapes']