Reputation: 71
I have a dictionary such as:
{'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'}}
I am wondering how to change just the number values to ints instead of strings.
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)
Upvotes: 0
Views: 3029
Reputation: 85785
Instead of just adding the values into the dictionary obj[key] = val
first check if the value should be stored as float
. We can do this by using regular expression
matching.
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
Note: you will need to import the python regular expression module re
by adding this line to the top of your script: import re
Probably wasting some 0's
and 1's
here but please read these:
Stop trying to 'get teh codez' and start trying develop your problem solving and programming ability otherwise you will only get so far..
Upvotes: 2
Reputation: 1328
If this is a one-level recursive dict, as in your example, you can use:
for i in the_dict:
for j in the_dict[i]:
try:
the_dict[i][j] = int (the_dict[i][j])
except:
pass
If it is arbitrarily recursive, you will need a more complex recursive function. Since your question doesn't seem to be about this, I will not provide an example for that.
Upvotes: 0
Reputation: 113955
I suspect that this is based on your previous question. If that is the case, you should consider intifying the value of "Orbital Radius" before you put it in your dictionary. My answer on that post actually does this for you:
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
But if you really want to process the numbers in the dictionary after you've created it, here's how you can do it:
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])
Hope this helps
Upvotes: 1