siva
siva

Reputation: 2145

How can I convert string values from a dictionary, into int/float datatypes?

I have a list of dictionaries as follows:

list = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ]

How do I convert the values of each dictionary inside the list to int/float?

So it becomes:

list = [ { 'a':1 , 'b':2 , 'c':3 }, { 'd':4 , 'e':5 , 'f':6 } ]

Upvotes: 52

Views: 205054

Answers (9)

twil
twil

Reputation: 103

I came here with a slightly different need: My dict just contained some integer strings.
I wanted a flexible solution where I do not have to specify the concrete keys to convert.

This is what I came up with (follows the Ask for forgiveness, not for permission credo)

        for k, v in myDict.items():
            try:
                myDict[k] = int(v)
                # Alternative
                # myDict.update({k: int(v)})
            except Exception:
                continue

Upvotes: 0

betontalpfa
betontalpfa

Reputation: 3752

A more general way using this number converter based on this answer.

def number(a, just_try=False):
    try:
        # First, we try to convert to integer.
        # (Note, that all integers can be interpreted 
        #  as float and hexadecimal numbers.)
        return int(a)
    except:
        # The order of the following conversions doesn't matter.
        # The integer conversion has failed because `a` 
        # contains hexadecimal digits [x,a-f] or a 
        # decimal point ['.'], but not both.
        try:
            return int(a, 16)
        except:
            try:
                return float(a)
            except:
                if just_try:
                    return a
                else:
                    raise


# The conversion:
[dict([a, number(x)] for a, x in b.items()) for b in list]

This will handle integer, float, and hexadecimal formats.

Upvotes: 1

emilpmp
emilpmp

Reputation: 1736

For Python 3,

    for d in list:
        d.update((k, float(v)) for k, v in d.items())

Upvotes: 2

raton
raton

Reputation: 428

  newlist = []              # Make an empty list
  for i in list:            # Loop to hv a dict in list
     s = {}                 # Make an empty dict to store new dict data
     for k in i.keys():     # To get keys in the dict of the list
         s[k] = int(i[k])   # Change the values from string to int by int func
     newlist.append(s)      # To add the new dict with integer to the list

Upvotes: 1

Powertieke
Powertieke

Reputation: 2408

We have got to love list comprehensions.

[dict([a, int(x)] for a, x in b.items()) for b in list]

(Remark: for Python 2-only code, you may use "iteritems" instead of "items")

Upvotes: 55

Jonathan Sternberg
Jonathan Sternberg

Reputation: 6677

If that's your exact format, you can go through the list and modify the dictionaries.

for item in list_of_dicts:
    for key, value in item.iteritems():
        try:
            item[key] = int(value)
        except ValueError:
            item[key] = float(value)

If you've got something more general, then you'll have to do some kind of recursive update on the dictionary. Check if the element is a dictionary, if it is, use the recursive update. If it's able to be converted into a float or int, convert it and modify the value in the dictionary. There isn't any built-in function for this and it can be quite ugly (and non-Pythonic since it usually requires calling isinstance).

Upvotes: 8

martineau
martineau

Reputation: 123531

To handle the possibility of int, float, and empty string values, I'd use a combination of a list comprehension, dictionary comprehension, along with conditional expressions, as shown:

dicts = [{'a': '1' , 'b': '' , 'c': '3.14159'},
         {'d': '4' , 'e': '5' , 'f': '6'}]

print [{k: int(v) if v and '.' not in v else float(v) if v else None
            for k, v in d.iteritems()}
               for d in dicts]

# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]

However dictionary comprehensions weren't added to Python 2 until version 2.7. It can still be done in earlier versions as a single expression, but has to be written using the dict constructor like the following:

# for pre-Python 2.7

print [dict([k, int(v) if v and '.' not in v else float(v) if v else None]
            for k, v in d.iteritems())
                for d in dicts]

# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]

Note that either way this creates a new dictionary of lists, instead of modifying the original one in-place (which would need to be done differently).

Upvotes: 1

Paolo
Paolo

Reputation: 21136

If you'd decide for a solution acting "in place" you could take a look at this one:

>>> d = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ]
>>> [dt.update({k: int(v)}) for dt in d for k, v in dt.iteritems()]
[None, None, None, None, None, None]
>>> d
[{'a': 1, 'c': 3, 'b': 2}, {'e': 5, 'd': 4, 'f': 6}]

Btw, key order is not preserved because that's the way standard dictionaries work, ie without the concept of order.

Upvotes: 1

Jim
Jim

Reputation: 3284

for sub in the_list:
    for key in sub:
        sub[key] = int(sub[key])

Gives it a casting as an int instead of as a string.

Upvotes: 36

Related Questions