Question

Python Modify your program from Learning Journal Unit 7 to read dictionary items from a file...

Python

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.

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.

Assignment from Learning Journal Unit 7:

Create a Python dictionary that returns a list of values for each key. The key can be whatever type you want.

Design the dictionary so that it could be useful for something meaningful to you. Create at least three different items in it. Invent the dictionary yourself. Do not copy the design or items from some other source.

Next consider the invert_dict function from Section 11.5 of your textbook.

# From Section 11.5 of:
# Downey, A. (2015). Think Python: How to think like a computer scientist. Needham, Massachusetts: Green Tree Press.

def invert_dict(d):
inverse = dict()
for key in d:
  val = d[key]
if val not in inverse:
inverse[val] = [key]
else:
inverse[val].append(key)
return inverse

Modify this function so that it can invert your dictionary. In particular, the function will need to turn each of the list items into separate keys in the inverted dictionary.

Run your modified invert_dict function on your dictionary. Print the original dictionary and the inverted one.

Include your Python program and the output in your Learning Journal submission.

Describe what is useful about your dictionary. Then describe whether the inverted dictionary is useful or meaningful, and why.

Program I wrote from Learning Journal Unit 7:

spanish_dict = {"Hola" : "Hello", "Felicidad" : "Happiness", "Amor" : "Love", "Gato" : "Cat", "Pero" : "Dog", "Gracias" : "Thank you", "Adios" : "Good bye", "Si" : "Yes", "Venir" : "To Come", "Decir" : "To say"}

def invert_dict(x):
inverse = dict()

for key1 in x.keys():
list_items = x.get(key1)
inverse[list_items]=key1
return inverse

print(invert_dict(spanish_dict))

0 0
Add a comment Improve this question Transcribed image text
✔ Recommended Answer
Answer #1

Note: Done accordingly. Please comment for any problem. Please Uprate. Thanks

Code:

import csv
def readFile():
filename="file.txt"
dictionary={}
with open(filename) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
key=row[0]
value=row[1]
dictionary[key]=value
return dictionary
  
  
def invert_dict(x):
inverse = dict()
for key1 in x.keys():
list_items = x.get(key1)
inverse[list_items]=key1
return inverse

def printResultToFile(data):
file1 = open("result.txt","w")
for key in data:
file1.write(key+","+data[key]+"\n")
file1.close()
  
data=readFile()
data=invert_dict(data)
printResultToFile(data)

Code screenshot:

1 import csv 2 def readFile(): filename=file.txt dictionary={ } with open(filename) as csv_file: csv_reader - csv.reader(cs

file.txt

Hola,Hello
Felicidad,Happiness
Amor,Love
Gato,Cat
Pero,Dog
Gracias,Thank you
Adios,Good bye
Si,Yes
Venir,To Come
Decir,To Say

result.txt

Hello,Hola
Happiness,Felicidad
Love,Amor
Cat,Gato
Dog,Pero
Thank you,Gracias
Good bye,Adios
Yes,Si
To Come,Venir
To Say,Decir

Add a comment
Answer #2

This one took some trial and error, but finally able to get this correct. With my original list, I had three entries for each (with the position, point accumulation, and time needed or if control/position was required), so I cut it back to two as it would be easier to code this. 


import csv  

def readFile():  

    filename="file.txt"  

    dictionary={}

    with open(filename) as csv_file: 

        csv_reader = csv.reader(csv_file, delimiter=',')

        for row in csv_reader:

            key=row[0]

            value=row[1]

            dictionary[key]=value

        return dictionary

  

  

def invert_dict(x): 

    inverse = dict()

    for key1 in x.keys():

        list_items = x.get(key1)

        inverse[list_items]=key1

    return inverse


def printResultToFile(data):

    file1 = open("result.txt","w")

    for key in data:

        file1.write(key+","+data[key]+"\n")

    file1.close()

  


data=readFile()

data=invert_dict(data)

printResultToFile(data)


print (readFile())

print ('----------------------------------------------------------------------')

print (data)


Output:

{'Back control': '4 seconds', 'Mount': ' 4 seconds', 'Guard Pass': ' position', 'Knee on Belly': ' 3 seconds', 'Takedown': ' position', 'Sweep': ' control ', 'Submission Attempt': ' strong', 'Penalty': ' Minus 1', 'DQ': ' End of match', 'Side Control': ' position '}

----------------------------------------------------------------------

{'4 seconds': 'Back control', ' 4 seconds': 'Mount', ' position': 'Takedown', ' 3 seconds': 'Knee on Belly', ' control ': 'Sweep', ' strong': 'Submission Attempt', ' Minus 1': 'Penalty', ' End of match': 'DQ', ' position ': 'Side Control'}

>>> 


File.txt (see attached as well) 

Back control,4 seconds

Mount, 4 seconds

Guard Pass, position

Knee on Belly, 3 seconds

Takedown, position

Sweep, control 

Submission Attempt, strong

Penalty, Minus 1

DQ, End of match

Side Control, position 


result.txt (see attached) 

4 seconds,Back control

 4 seconds,Mount

 position,Takedown

 3 seconds,Knee on Belly

 control ,Sweep

 strong,Submission Attempt

 Minus 1,Penalty

 End of match,DQ

 position ,Side Control

 Added in three more items as requested in the .txt file with penalty, DQ and Side Control for the additions. 


source: University of the people assignment
answered by: Mike D
Add a comment
Know the answer?
Add Answer to:
Python Modify your program from Learning Journal Unit 7 to read dictionary items from a file...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 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:

    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...

  • Hello, Similar questions like this have been previously answered, but this question is different because it has only one...

    Hello, Similar questions like this have been previously answered, but this question is different because it has only one part while similar questions have 2 parts and their solutions is a combination of the 2 parts. I have not been able to find an absolute solution for this part. QUESTION: 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...

  • Help me with this Python Question a. build_word_dictionary (filename) – This builds a word dictionary indexed...

    Help me with this Python Question a. build_word_dictionary (filename) – This builds a word dictionary indexed by words from the file who’s filename is provided as an argument. It uses the words as keys and the count of occurrences as values. It returns the dictionary it constructed. It can use the ‘tokenize()’ function that is provided in the lecture slides. b. inverse_dict(dict) – This method takes a dictionary (generated by build_word_dictionary() and inverts it (as was done with students and...

  • (IN PYTHON) You are to develop a Python program that will read the file Grades-1.txt that...

    (IN PYTHON) You are to develop a Python program that will read the file Grades-1.txt that you have been provided on Canvas. That file has a name and 3 grades on each line. You are to ask the user for the name of the file and how many grades there are per line. In this case, it is 3 but your program should work if the files was changed to have more or fewer grades per line. The name and...

  • Write a Python equivalent program for the Unix spell utility. You can use the dictionary at /usr/...

    Write a Python equivalent program for the Unix spell utility. You can use the dictionary at /usr/share/dict/words (if you machine does not have it, you can copy it from a Linux machine such as npu29). The minimum requirement is to check if each word in the file exists in the dictionary as is (case insensitive). Your spell checker should inlcude at least two features: 1. Check the simple plural forms (add s or es). 2. Check the simple verb past...

  • Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in...

    Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since...

  • Python 3.7 Coding assignment This Program should first tell users that this is a word analysis...

    Python 3.7 Coding assignment This Program should first tell users that this is a word analysis software. For any user-given text file, the program will read, analyze, and write each word with the line numbers where the word is found in an output file. A word may appear in multiple lines. A word shows more than once at a line, the line number will be only recorded one time. Ask a user to enter the name of a text file....

  • Write a Python program that reads text from a file, encrypts it with a Caesar Cipher,...

    Write a Python program that reads text from a file, encrypts it with a Caesar Cipher, and displays the encrypted text. Do not process punctuation. Convert the original string to all lower-case before encrypting it.

  • In python, PART A: I am trying to get a dictionary with size(4, 5, 6) as...

    In python, PART A: I am trying to get a dictionary with size(4, 5, 6) as keys and an array for key containing a list of values (words from file of respective size) associated with those keys I am reading from a file of strings, where I am only interested with words of length 4, 5, and 6 to compute my program reading the text file line by line: At first, I have an empty dictionary then to that I...

  • Write a Python program named aIP.py which will read data from a file named wireShark.txt and...

    Write a Python program named aIP.py which will read data from a file named wireShark.txt and extract all the pairs of source and destination ip addresses and output them in pairs to another file called IPAddresses.txt , one per line, listing source and destination. Example of output: Source                      Destination 192.168.1.180         239.255.255.250 Detailed Requirements: You will read from a file called wireShark.txt which, to avoid problems with finding paths, will be located in the same directory as your code You will...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT