【问题标题】:how to change string values in dictionary to int values如何将字典中的字符串值更改为int值
【发布时间】:2012-11-23 21:12:21
【问题描述】:

我有一本字典,例如:

{'Sun': {'Satellites': 'Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Ceres,Pluto,Haumea,Makemake,Eris', 'Orbital Radius': '0', 'Object': 'Sun', 'RootObject': 'Sun', 'Radius': '20890260'}, 'Earth': {'Period': '365.256363004', 'Satellites': 'Moon', 'Orbital Radius': '77098290', 'Radius': '63710.41000.0', 'Object': 'Earth'}, 'Moon': {'Period': '27.321582', 'Orbital Radius': '18128500', 'Radius': '1737000.10', 'Object': 'Moon'}}

我想知道如何将数字值更改为整数而不是字符串。

def read_next_object(file):    
        obj = {}               
        for line in file:      
                if not line.strip(): continue
                line = line.strip()                        
                key, val = line.split(": ")                
                if key in obj and key == "Object": 
                        yield obj                       
                        obj = {}                              
                obj[key] = val

        yield obj              

planets = {}                   
with open( "smallsolar.txt", 'r') as f:
        for obj in read_next_object(f): 
                planets[obj["Object"]] = obj    

print(planets)                

【问题讨论】:

    标签: python dictionary python-3.x


    【解决方案1】:

    首先检查值是否应存储为float,而不是仅仅将值添加到字典obj[key] = val。我们可以通过使用regular expression 匹配来做到这一点。

    if re.match('^[0-9.]+$',val):  # If the value only contains digits or a . 
        obj[key] = float(val)      # Store it as a float not a string
    else: 
        obj[key] = val             # Else store as string 
    

    注意:您需要导入 python 正则表达式模块re,方法是将此行添加到脚本顶部:import re

    可能在这里浪费了一些 0's1's阅读以下内容:

    1. The Python tutorial

    2. Python data types

    3. Importing Python modules

    4. Regular expression HOWTO with python

    停止尝试'get teh codez'并开始尝试发展你的问题解决和编程能力,否则你只会走这么远..

    【讨论】:

    • 有没有办法遍历整个字典而不是创建一个新列表,而只是更改当前字典??
    【解决方案2】:
    s = '12345'
    num = int(s) //num is 12345
    

    【讨论】:

    • 入字典前先处理好,粗制滥造后试图清理是不行的。
    • 但文本文件中有文字和其他东西>>
    • 是的,这往往会发生。
    【解决方案3】:

    我怀疑这是基于your previous question。如果是这种情况,您应该考虑在将“轨道半径”的值放入字典之前将其输入。我在那个帖子上的回答实际上是为你做的:

    elif line.startswith('Orbital Radius'):
    
        # get the thing after the ":". 
        # This is the orbital radius of the planetary body. 
        # We want to store that as an integer. So let's call int() on it
        rad = int(line.partition(":")[-1].strip())
    
        # now, add the orbital radius as the value of the planetary body in "answer"
        answer[obj] = rad
    

    但是,如果您真的想在创建字典后处理字典中的数字,可以这样做:

    def intify(d):
        for k in d:
            if isinstance(d[k], dict):
                intify(d[k])
            elif isinstance(d[k], str):
                if d[k].strip().isdigit():
                    d[k] = int(d[k])
                elif all(c.isdigit() or c=='.' for c in d[k].strip()) and d[k].count('.')==1:
                    d[k] = float(d[k])
    

    希望对你有帮助

    【讨论】:

    • 我正在使用一个不同的程序然后之前所以有没有像这样的 for 循环然后迭代字典的方法?
    • @tomsmith:注意intify() 函数是如何使用recursion的。
    • @inspectorG4dget 当我使用上面的程序 intify 并打印它输出“none”的 dict ??????
    • @tomsmith:那是因为它就地修改了dict。没有返回值
    【解决方案4】:

    如果这是一个一级递归字典,如您的示例所示,您可以使用:

    for i in the_dict:
        for j in the_dict[i]:
            try:
                the_dict[i][j] = int (the_dict[i][j])
            except:
                pass
    

    如果它是任意递归的,你将需要一个更复杂的递归函数。由于您的问题似乎与此无关,因此我不会为此提供示例。

    【讨论】:

    • 不处理递归字典,因此不适用于问题中提供的输入。
    • 啊,对,我没有看到它是一个递归字典。现在改了。
    猜你喜欢
    • 2019-07-17
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 2020-08-07
    • 2014-12-27
    相关资源
    最近更新 更多