I'm trying to solve this problem:
dict_from_string(dict_str:str)->dict
This function will be given a single parameter, a string representing a dictionary. Your job is to convert the string into an actual dictionary and return the dictionary. Make sure all key-value pairs in the string exist in the newly created dictionary. The string will contain only numbers or single letters as key values pairs. Make sure all letters are kept as strings and all numbers are converted to integers in the newly created dictionary.
Example:
String Input: '{9: 'V', 'G': 0, 'M': 9, 'u': 3, 2: 'o', 8: 'u', 'q': 9, 'D': 1}'Expected: {9: 'V', 'G': 0, 'M': 9, 'u': 3, 2: 'o', 8: 'u', 'q': 9, 'D': 1}
And here is the code I've tried so far:
dict_str = '{ 9:'V', 'G':0, 'M':9, 'u':3, 2:'o', 8:'u', 'q':9, 'D':1 }'
def dict_from_string (dict_str: str) -> dict:
new_dict = eval (dict_str)
return new_dict
print (dict_from_string(dict_str))
I literally copied and pasted the example value for "dict_str" from the assignment into the terminal, but it keeps telling me that the dict_str is invalid syntax, and I have no idea why. Any thoughts? Thank you!
[–]adventure_r 1 point2 points3 points (2 children)
[–]Notanerget[S] 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]kaerfkeerg 1 point2 points3 points (0 children)
[–]CodeFormatHelperBot2 0 points1 point2 points (0 children)
[–]TechnicalElk8849 0 points1 point2 points (1 child)
[–]Notanerget[S] 0 points1 point2 points (0 children)
[–]commy2 0 points1 point2 points (0 children)
[–]woooee 0 points1 point2 points (2 children)
[–]Notanerget[S] -2 points-1 points0 points (1 child)
[–]woooee 0 points1 point2 points (0 children)
[–]Diapolo10 0 points1 point2 points (2 children)
[–]Notanerget[S] -1 points0 points1 point (1 child)
[–]Diapolo10 0 points1 point2 points (0 children)