开发者

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

开发者 https://www.devze.com 2023-02-16 20:25 出处:网络
I have 开发者_如何转开发a list of dictionaries as follows: list = [ { \'a\':\'1\' , \'b\':\'2\' , \'c\':\'3\' }, { \'d\':\'4\' , \'e\':\'5\' , \'f\':\'6\' } ]

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 } ]

Thanks.


Gotta 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")


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.


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's no built-in function for this and it can be quite ugly (and non-pythonic since it usually requires calling isinstance).


For python 3,

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


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.


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).


  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


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 integer can be interpreted as float and hex number.)
        return int(a)
    except:
        # The order of the following convertions doesn't matter.
        # The integer convertion has failed because `a` contains hex 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消