-2

The following program is given:

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)
     print(inverse)
Days = dict()
Days['Monday'] = 'First Day of the Week'
Days['Tuesday'] = 'Second Day of the Week'
Days['Wednesday'] = 'Third Day of the Week'
Days['Thursday'] = 'Fourth Day of the Week'
Days['Friday'] = 'Fith Day of the Week'
Days['Saturday'] = 'Sixth Day of the Week'
Days['Sunday'] = 'Seventh Day of the Week'
invert_dict(Days)

I have no clue, nor idea how am I supposed to do the following tasks:

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.

I have the 2 files that I need, but I can't figure out how I have to do this.

The code below is as far as I got and I'm getting a 'str' object has no attribute 'read' error on the as reader line.

g='file 1 location'
h='file 2 location' # Where to write inverted content of file 1
import ast
import os

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)
     print(inverse)

Days = dict()
Days['Monday'] = 'First Day of the Week'
Days['Tuesday'] = 'Second Day of the Week'
Days['Wednesday'] = 'Third Day of the Week'
Days['Thursday'] = 'Fourth Day of the Week'
Days['Friday'] = 'Fith Day of the Week'
Days['Saturday'] = 'Sixth Day of the Week'
Days['Sunday'] = 'Seventh Day of the Week'
invert_dict(Days)
with open(g,encode="utf-8") as reader
    h=reader.readlines(g)
with open(g,'w',encode="utf-8") as a_writer
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    You should, please, tell us what you are trying to do. In particular, the error you mention appears to be because there's no colon following the `with open` statement. (There's none at the end of either of them.) – Bill Bell Jan 04 '20 at 18:15
  • As I've stated above, I'm trying to print the inverted output of file1 to file 2 – Cintar Lehel Jan 04 '20 at 18:16
  • I'm using g and h as refferences to the file locations so the code looks a bit cleaner. I hate it when I have 20-30 lines of code and they are long. It helps me read the code cleanly. that's why there is no colon after `with open` – Cintar Lehel Jan 04 '20 at 18:18
  • I think the formatting of the code is broken, you should check it, part of the program looks duplicated and not escaped properly. It would also be good if you could share some information about the data, in order to have a [mcve]. – AMC Jan 04 '20 at 18:20
  • @CintarLehel There needs to be a colon, I'm not sure I understand why you omitted it, since the first part of your comment is just about the length of the lines of code. – AMC Jan 04 '20 at 18:22
  • @AMC : The only new part of this code, starts with the 2 file locations g and H and the with open statements which I've freshly wrote. Still the same issue. Hang on a second. Shouldn't the code first invert the contents of file one then convert it to string and transfer it to the second file and then convert it back to a list ? – Cintar Lehel Jan 04 '20 at 18:23
  • @AMC I've replaced the G and H with the respective file locations . Still the same error. – Cintar Lehel Jan 04 '20 at 18:25
  • @CintarLehel _I've replaced the G and H with the respective file locations . Still the same error._ Pardon? – AMC Jan 04 '20 at 18:27
  • 1
    @CintarLehel I don't even know what _invert the contents_ means, you haven't explained that. Please fix the code in your post. – AMC Jan 04 '20 at 18:28
  • `g='file 1 location' h='file 2 location to which the inverted content of file 1 must me written to'` This part of the code G and H, I'm using variables to store the file location as a string, so when I have to work on the files I just have to type in to the code G or H and thus not needing a colon in `with open`. I've switched in the code the G and H calling with the actual file paths that need to be worked on. File G should have the contents of the `Days` dictionary and file H should have the inverted contents of G. I don't know how to explain it any clearer. – Cintar Lehel Jan 04 '20 at 18:34
  • @CintarLehel I don't see how it's related to what I wrote. I know what `g` and `h` are, that's not an issue. – AMC Jan 04 '20 at 18:56
  • It's difficult to understand how you're getting the `no attribute 'read'` error from that line, but there should be a `:` colon character at the end of `with` statements: i.e. `with open(g,encode="utf-8") as reader:`. Note that there's one missing on the `as a_writer` line near the same spot. – martineau Jan 04 '20 at 19:16
  • Progress update : Now I'm getting `TypeError: 'str' object is not callable` Error. I do not have str defined anywhere . – Cintar Lehel Jan 04 '20 at 19:23
  • @CintarLehel That error message isn't about a variable `str`. Please update your post with the full error message. – AMC Jan 04 '20 at 19:45
  • In light of your comment on the answer saying _That's what I'm actually struggling with. Is the fact that I do not understand how does the above output that you received get to the second text file._, **I think this should be closed**. If it is edited heavily to reflect the above comment, it should be closed as a duplicate or as too broad/off-topic. There are **plenty** of resources on simple file IO. – AMC Jan 04 '20 at 22:27

2 Answers2

0

I don't want to give you the full answer because this seems like homework but this should be enough to get you started, the code is commented.

Days = dict()
Days['Monday'] = 'First Day of the Week'
Days['Tuesday'] = 'Second Day of the Week'
Days['Wednesday'] = 'Third Day of the Week'
Days['Thursday'] = 'Fourth Day of the Week'
Days['Friday'] = 'Fith Day of the Week'
Days['Saturday'] = 'Sixth Day of the Week'
Days['Sunday'] = 'Seventh Day of the Week'

def invert(dic):
    a = list(dic.items()) # Casts dict to list
    a.reverse() # reverses lsit
    return dict(a) # cast back to dictionary and return

with open("Output.txt", 'w') as f: # Opens a file for WRITING "Output.txt" in CURRENT working directory
                                   # Creates a new file if it does not exist or truncates the file if it exists
   for i in invert(Days).items():   # loop through keys and values      
       f.write(f"{i}\n")    # writes the items and adds a new line

This inverts the order of the dictionary, it is confusing (I'm still not 100% on what you need to do exactly) when you say "invert" because you can "invert" a dictionary many ways, a common scenario is to invert the keys and values as can be seen here.

the Output.txt looks like this:

('Sunday', 'Seventh Day of the Week')
('Saturday', 'Sixth Day of the Week')
('Friday', 'Fith Day of the Week')
('Thursday', 'Fourth Day of the Week')
('Wednesday', 'Third Day of the Week')
('Tuesday', 'Second Day of the Week')
('Monday', 'First Day of the Week')

I assume you will need to format it properly and with this information you should be able to write the ordered dictionary to a file, read that file in, and rewrite the inverted file to another file using the constraints set for you.

BpY
  • 403
  • 5
  • 12
  • Thank you for taking the time to answer my question. I would like to point out, that my destination of the output should be a second text file. That's what I'm actually struggling with. Is the fact that I do not understand how does the above output that you received get to the second text file. – Cintar Lehel Jan 04 '20 at 21:01
  • `with open("Output.txt", 'w') as f:` the 'w' means that you open the file (in this case Output.txt) in "write" mode i.e to write to the file, you could call output anything you want with any extension. alternatively you could use 'r+' which opens the file for reading and writing [mor info available here](https://docs.python.org/3/tutorial/inputoutput.html) – BpY Jan 04 '20 at 21:15
  • 1
    @CintarLehel You need to specify in your post what the issue actually is, then. You write _That's what I'm actually struggling with. Is the fact that I do not understand how does the above output that you received get to the second text file_, yet your post doesn't make that clear. – AMC Jan 04 '20 at 22:25
0

I've figured it out! Thank you so much for the help! I overthought everything (lel) So anyway, this is what my program has to do . Take the below dictionary and basically flip it upside down as you said @BSQL, but my output had to be the flipped dictionary and that's where I started to overcomplicate things with trying to store the dictionary in a file and then (mambo jambo overthinking)

Days = dict()
Days['Monday'] = 'First Day of the Week'
Days['Tuesday'] = 'Second Day of the Week'
Days['Wednesday'] = 'Third Day of the Week'
Days['Thursday'] = 'Fourth Day of the Week'
Days['Friday'] = 'Fith Day of the Week'
Days['Saturday'] = 'Sixth Day of the Week'
Days['Sunday'] = 'Seventh Day of the Week'

def invert(dic):
    a = list(dic.items()) # Casts dict to list
    a.reverse() # reverses lsit
    return dict(a) # cast back to dictionary and return

with open(h, 'w') as f: # Opens a file for WRITING "Output.txt" in CURRENT working directory
                                   # Creates a new file if it does not exist or truncates the file if it exists
   for i in invert(Days).items():   # loop through keys and values
       f.write(f"{i}\n")    # writes the items and adds a new line```
  • _flip it upside down_, _flipped dictionary_, ... Have you been looking to print the dictionary in **reverse order** this entire time? – AMC Jan 04 '20 at 22:24
  • Reverse order from a file in to another file. I'm stuck again (omg)@AMC – Cintar Lehel Jan 04 '20 at 22:29
  • How are you stuck? Can you please share your data? – AMC Jan 04 '20 at 22:31
  • @AMC : The program is creating my desired output, however, I cannot make the `Days` dictionary written as above in to the source text file from which the program has to execute the operation. So it should be : copy dictionary to source file , copy to destination file with the output being a reveresed order. I cannot figure out how to copy it . I've tried google, didn't help in my case as the google examples are `1 : "text" not `"text" : "text" ` as in my case. – Cintar Lehel Jan 05 '20 at 00:00
  • 1
    use what I have above just omit the inverse function and call the file anything e.g *foo.txt* then read in *foo.txt* (perhaps using information from my **comment** above) and write it to a file exactly like above called "bar.txt" for example. (NOTE: foo and bar are just conventional placeholder names you can change these to anything you like for example "input_file" and "output_file" may be more clear to use here – BpY Jan 05 '20 at 00:51
  • @CintarLehel Please share your data. Not having the data makes it even more difficult to understand this file ballet. I feel like the more I learn about the program, the less I understand the problem. _So it should be : copy dictionary to source file_ Be careful! When you write _source file_, I think **Python source file**, is that what you mean? You really need to be more specific. – AMC Jan 05 '20 at 01:22