Skip to main content
 首页 » 编程设计

python之将 dict 中的所有值转换为它们的实际类型

2025年05月04日17shihaiming

假设我有这本字典,里面填满了各种字符串值:

dictionary = { "name": "Andrew", "age": "34", "is_good_enought": "True", "something": "None" } 

如何将所有字符串值转换为它们所代表的确切数据类型?

预期结果:

dictionary = { "name": "Andrew", "age": 34, "is_good_enought": True, "something": None} 

请您参考如下方法:

你可以尝试这样的事情:

from ast import literal_eval 
 
for i, v in dictionary.items(): 
    try: 
        dictionary[i] = literal_eval(v) 
    except ValueError: 
        pass 

来自文档:

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.