Home > OS >  Facing this error :- TypeError: unsupported operand type(s) for -: 'str' and 'float&#
Facing this error :- TypeError: unsupported operand type(s) for -: 'str' and 'float&#

Time:04-17

Query) I was trying to plot a graph, using coordinates mentioned in dict_A, but the operation halted showing the error

TypeError: unsupported operand type(s) for -: 'str' and 'float'.

import json
import matplotlib.pyplot as plt
from ast import literal_eval


def any_function():

    with open('contents.txt') as f:
        A               = f.readline()  
        dict_A          = json.loads(A)         # converts to dictionary

        B = dict((literal_eval, i) for i in dict_A.items()) #convert k, v to int

#plotting a simple graph-based on coordinates mentioned in A.

        x = [i[0]  for i in  B.values()]
        y = [i[1]  for i in  B.values()]
        size = 50
        offset = size/100.
        for i, location in enumerate(zip(x,y)):
            plt.annotate(i 1, ( location[0]-offset, location[1]-offset), zorder=10 )  
        
    return {'A':dict_A}
    

any_function()                 #calling the function 


This is my data inside the text file (contents.txt)

{"1":"[0,0]", "2":"[5, 0]", "3":"[6,0]","4":"[3,5]"}

Error coming

runfile('D:/python programming/a new program 2021/testing 9 input.py', wdir='D:/python programming/a new program 2021')
Traceback (most recent call last):

  File "D:\python programming\a new program 2021\testing 9 input.py", line 37, in <module>
    a = any_function()

  File "D:\python programming\a new program 2021\testing 9 input.py", line 32, in any_function
    plt.annotate(i 1, ( location[0]-offset, location[1]-offset), zorder=10 )

TypeError: unsupported operand type(s) for -: 'str' and 'float'

CodePudding user response:

I`m not sure what you think this is doing, but it's not what you expect:

B = dict((literal_eval, i) for i in dict_A.items()) #convert k, v to int

That doesn't convert anything to int. The inner part of that:

(literal_eval, i)

will product a tuple that contains the literal_eval function object, and the item pairs from your dictionary. I'm guessing you didn't print(B) to see what you were building. Since all of the items have the same key, what you end up with is this:

>>> B = dict((literal_eval, i) for i in t.items()) #convert k, v to int
>>> B
{<function literal_eval at 0x7f531ddcb5e0>: ('4', '[3,5]')}

What you actually want is to CALL literal_eval:

>>> B = dict((literal_eval(k), literal_eval(v)) for k,v in t.items())
>>> B
{1: [0, 0], 2: [5, 0], 3: [6, 0], 4: [3, 5]}
>>> 
  • Related