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:
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:
Here is my code for assignment 7 that needs to be modified;
alphabet = "abcdefghijklmnopqrstuvwxyz" test_dups = ["zzz","dog","bookkeeper","subdermatoglyphic","subdermatoglyphics"] test_miss = ["zzz","subdermatoglyphic","the quick brown fox jumps over the lazy dog"] def histogram(s): d = dict() for c in s: if c not in d: d[c]=1 else: d[c] += 1 return d #part 1 def has_duplicates(): for string in test_dups: dictionary=histogram(string) duplicates=False for ch in dictionary.keys(): if dictionary[ch] > 1: duplicates=True break if duplicates==True: print(string,"has duplicates") else: print(string,"has no duplicates") #part 2 def missing_letters(string): answer="" for ch in alphabet: if ch not in string: answer=answer+ch return answer has_duplicates() for i in test_miss: answer=missing_letters(i) if len(answer)>=1: print(i,"is missing letters",answer) else: print(i,"uses all the letters")
Solution for the above Problem:
/copyable code
def invert_Dictionary(x):
inverse=dict()
for key1 in x.keys():
list_items = x.get(key1)
inverse[list_items]=key1
return inverse
def readfile(file_name):
x=dict()
with open(file_name,'r') as infile:
for line1 in infile.readlines():
line1=line1.strip().split(':')
x[line1[0]]=line1[1]
print('file Read',x)
return x
def writefile(invert_d,file_name):
with open(file_name,'w+') as wtfile:
for key1,value1 in invert_d.items():
wtfile.write(str(key1)+':'+str(value1)+'\n')
def main():
x = readfile('dic.txt')
invt_d = invert_Dictionary(x)
print('Dictionary inverted',invt_d)
writefile(invt_d,'inverted_dic.txt')
main()
Screenshot:
Output: