python字典中的值可以更改吗_关于python:如何将字典中的字符串值更改为int值

我有一本字典,比如:

{'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'}}

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

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)

不要只是将值添加到字典obj[key] = val中,而是首先检查该值是否应存储为float。我们可以通过使用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's和1's,但请阅读:

python教程

python数据类型

导入python模块

正则表达式howto with python

停止尝试"获取teh codez",开始尝试开发你的问题解决和编程能力,否则你只能做到这一步。

有没有一种方法可以遍历整个词典,而不是创建一个新的列表,而是只更改当前的措辞??

投票结束

我怀疑这是基于你以前的问题。如果是这样的话,在你把"轨道半径"放进字典之前,你应该考虑去解释它的值。我在那篇文章上的回答实际上是为你做的:

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循环,然后在dict上迭代?

@Tomsmith:注意intify()函数是如何使用递归的。

到目前为止我的程序还不管用,是吗

正如我刚才编辑的^^^

@当我使用上面的程序时,inspectorg4dget识别并打印它输出的dict"none"????????

@汤姆史密斯:那是因为它在适当的地方修改了dict。没有返回值

s = '12345'

num = int(s) //num is 12345

在字典里吗兄弟??

在你把它放进字典之前处理它,在劣质的解析之后尝试清理是不可能的。

但文本文件中有单词和所有内容>>

是的,这很可能发生。

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

for i in the_dict:

for j in the_dict[i]:

try:

the_dict[i][j] = int (the_dict[i][j])

except:

pass

如果它是任意递归的,则需要更复杂的递归函数。既然你的问题似乎与此无关,我就不举一个例子。

不处理递归dict,因此无法处理问题中提供的输入。

啊,对了,我没看到这是一个递归的口述。现在改了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值