Python:如何将字典的值列表转换为int/float from string?

时间:2021-05-12 21:43:08

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?

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

So it becomes:

所以它就变成:

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

Thanks.

谢谢。

6 个解决方案

#1


17  

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.

将其转换为int类型,而不是字符串。

#2


30  

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

(注:对于Python 2,只能使用“iteritems”而不是“items”)

#3


3  

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

如果您有更一般的内容,那么您必须对字典进行某种递归更新。检查元素是否是字典,如果是,使用递归更新。如果可以将其转换为浮点数或int数,则对其进行转换并修改字典中的值。它没有内置的函数,而且可能会很难看(而且不是python语言,因为它通常需要调用isinstance)。

#4


1  

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:

为了处理int、float和空字符串值的可能性,我将结合列表理解、字典理解和条件表达式,如下所示:

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:

然而,直到版本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}]

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

注意,这两种方法都创建了一个新的列表字典,而不是修改原来的列表(这需要以不同的方式进行)。

#5


0  

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.

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

#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

#1


17  

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.

将其转换为int类型,而不是字符串。

#2


30  

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

(注:对于Python 2,只能使用“iteritems”而不是“items”)

#3


3  

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

如果您有更一般的内容,那么您必须对字典进行某种递归更新。检查元素是否是字典,如果是,使用递归更新。如果可以将其转换为浮点数或int数,则对其进行转换并修改字典中的值。它没有内置的函数,而且可能会很难看(而且不是python语言,因为它通常需要调用isinstance)。

#4


1  

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:

为了处理int、float和空字符串值的可能性,我将结合列表理解、字典理解和条件表达式,如下所示:

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:

然而,直到版本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}]

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

注意,这两种方法都创建了一个新的列表字典,而不是修改原来的列表(这需要以不同的方式进行)。

#5


0  

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.

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

#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