Home > Software design >  How to convert a dictionary value from a string to an int (Or how do I better write my code read it
How to convert a dictionary value from a string to an int (Or how do I better write my code read it

Time:04-18

I am attempting to open a text file the following way: enter image description here

However, the value is reading as a string as opposed to an int. How do I get the value from the text file to read as an int? For example a file reading CSCI 160:4 CSCI 289:3 EE 201:4 MATH 208:3 prints out as the dictionary {'CSCI 160': '4', 'CSCI 289': '3', 'EE 201': '4', 'MATH 208': '3'}

CodePudding user response:

After you create ClassDict you can convert all values to integers, for example:

ClassDict = {k: int(v) for k, v in ClassDict.items()}
print(ClassDict)

Prints:

{'CSCI 160': 4, 'CSCI 289': 3, 'EE 201': 4, 'MATH 208': 3}
  • Related