如何将字典中的字符串值转换为int / float数据类型?

时间:2011-03-15 19:10:52

标签: python string list dictionary int

我有一个字典列表如下:

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

如何将列表中每个字典的值转换为int / float?

所以它变成了:

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

感谢。

8 个答案:

答案 0 :(得分:38)

得到爱情列表理解。

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

备注:对于Python 2唯一的代码,您可以使用“iteritems”而不是“items”

答案 1 :(得分:21)

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

将转换为int而不是字符串。

答案 2 :(得分:4)

如果这是您的确切格式,您可以浏览列表并修改词典。

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

如果你有更通用的东西,那么你将不得不在字典上进行某种递归更新。检查元素是否是字典,如果是,则使用递归更新。如果它能够转换为float或int,则转换它并修改字典中的值。这里没有内置函数,它可能非常难看(并且非pythonic,因为它通常需要调用isinstance)。

答案 3 :(得分:2)

对于python 3,

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

答案 4 :(得分:1)

为了处理intfloat和空字符串值的可能性,我会使用列表推导,字典理解以及条件表达式的组合,如下所示:

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

然而,在版本2.7之前,字典理解没有添加到Python 2中。它仍然可以在早期版本中作为单个表达式完成,但必须使用dict构造函数编写,如下所示:

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

请注意,无论哪种方式,这都会创建一个新的列表字典,而不是就地修改原始字典(这需要以不同的方式完成)。

答案 5 :(得分:0)

如果你决定采用“就地”的解决方案,你可以看看这个:

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

顺便说一下,关键顺序不会被保留,因为这是标准词典的工作方式,即没有顺序概念。

答案 6 :(得分:0)

  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

答案 7 :(得分:0)

基于 this number converter 使用 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]

这将处理整数、浮点数和十六进制格式。

相关问题