Search code examples
pythondictionarysetevaltypeerror

having a string as dict and formatting it through eval (not subscriptable)


I never used this kind of command so this error makes me raise an eybrow. I'm trying to refactor my code so instead of an output like

'temp': 22,56, 'temp_max': 25.6, 'temp_min': 19.0, 'temp_kf': None

it shows simply 22,56. I found a code that said to us a dict:

s = "'temp': 18.72, 'temp_max': 20.0, 'temp_min': 17.0, 'temp_kf': None"
data = eval('{{{}}}'.format(s))
temperature1 = str(data['temp'])
print(temperature1)

where the output comes out like 18,72

So i tried to put my variable t as a string (which if printed gives the same exact output as the dict inside of s, only with current temperature numbers) inside of s.:

s = str(t))
data = eval('{{{}}}'.format(s))
temperature1 = str(data['temp'])
print(temperature1)

And this tells me s is unhashable, so i modified it in s = hash(str(t))

And now I get the error

TypeError: 'set' object is not subscriptable

Why is this so difficutlt?


Solution

  • I think the issue here is how you set up your dictionary, you actually only created a string that resembles a dictionary, take a look at this and then also look back at some other reference sources for the proper structure of a dictionary

    Solution

    dicta = {
        'temp': '22, 56', 'temp_max': 25.6, 'temp_min': 19.0, 'temp_kf': None
    }
    
    print(dicta['temp'])
    

    Output

    (xenial)vash@localhost:~/python$ python3.7 split.py 
    22, 56
    

    You can pretty it up with some labeling like so

    print(f"Temp: {dicta['temp']}")
    

    This prints:

    (xenial)vash@localhost:~/python$ python3.7 split.py 
    Temp: 22, 56