-2

I am asking this because I saw a dictionary produced from two different sources, in which one number is a float, and the same number is a string.

data = {'name': 'jack', 'confidence': '0.95'}

The 'confidence' is a float in once case, and a str in another case. Why is that?

conf = data.get('confidence')
marlon
  • 6,029
  • 8
  • 42
  • 76

3 Answers3

1

It all depends on how they decided to store value in the dict. But if you want to access the value, conf = float(data.get('confidence')) might be good for your use.

hoan duc
  • 70
  • 10
1

Values in a dictionary surrounded by quotes are strings. '0.95' is a string, but 0.95 is a float. You can use the isinstance built-in function:

conf = data.get('confidence')
if isinstance(conf, str):
    pass
elif isinstance(conf, float):
    pass
Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
0
conf = data.get('confidence')
try:
  conf = float(conf)
except:
  pass
user8426627
  • 903
  • 1
  • 9
  • 19