0

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)                
tom smith
  • 71
  • 3
  • 11

4 Answers4

2

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:

  1. The Python tutorial

  2. Python data types

  3. Importing Python modules

  4. Regular expression HOWTO with python

Stop trying to 'get teh codez' and start trying develop your problem solving and programming ability otherwise you will only get so far..

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
  • is there a way to iterate over the whole dictionary and not to create a new list but instead just change the current dictionay?? – tom smith Nov 24 '12 at 00:15
1
s = '12345'
num = int(s) //num is 12345
Lanaru
  • 9,421
  • 7
  • 38
  • 64
1

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

Community
  • 1
  • 1
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
0

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.

Bas Wijnen
  • 1,288
  • 1
  • 8
  • 17