简体   繁体   中英

How to use python dictionary values as integers, floats or booleans?

i am trying to read the dictionary values in python as integers or floats or booleans and not as strings. I have one text file with the following content:

Cat : 1 Food : 1.5 Enough : True

Until now i can read the text file and create the dictionary as following:

dict = {
  "Cat": "1",
  "Food": "1.5",
  "Enough": "True"
}

However what i would like to do is to read the keys as ints floats and booleans. I am thinking of something like:

if dict.key == "Cat": 
   dict.value is integer
if dict.key == "Food": 
   dict.value is float
if dict.key == "Enough": 
   dict.value is boolean

However i do not know how to write something like that. I would really appreciate anyones help or idea.

Ps. Another idea would be to have it read as a string from my text file and then convert it. But i still can not find a proper solution or any examples similar to what i am looking for.

you could use a meta dictionary with key being the key of your dictionary and value would be the type to convert to, defaulting to convert as string if key not found:

meta_dict = { "Cat": int, "Food": float, "Enough": bool }
my_dict = { "Cat": "1", "Food": "1.5", "Enough": "True", "misc":"other" }  # adding a string key for the demo

new_dict = { k:meta_dict.get(k,str)(v) for k,v in my_dict.items()}

print(new_dict)

prints:

{'Cat': 1, 'Food': 1.5, 'Enough': True, 'misc': 'other'}

if you don't have any string keys but only integers, floats and booleans, you could use ast.literal_eval to guess the type and convert to it:

import ast
my_dict = { "Cat": "1", "Food": "1.5", "Enough": "True" }
new_dict = { k:ast.literal_eval(v) for k,v in my_dict.items()}

In the future, save & reload your file as json so types are preserved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM