![](/img/trans.png)
[英]How to convert string values from a list inside a dictionary, into float datatypes?
[英]How to convert string values from a dictionary, into int/float datatypes?
我有一個字典列表如下:
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 } ]
謝謝。
必須愛列表理解。
[dict([a, int(x)] for a, x in b.items()) for b in list]
(備注:對於僅 Python 2 的代碼,您可以使用“iteritems”而不是“items” )
for sub in the_list:
for key in sub:
sub[key] = int(sub[key])
將其轉換為 int 而不是字符串。
如果這是您的確切格式,您可以瀏覽列表並修改字典。
for item in list_of_dicts:
for key, value in item.iteritems():
try:
item[key] = int(value)
except ValueError:
item[key] = float(value)
如果你有一些更一般的東西,那么你將不得不對字典進行某種遞歸更新。 檢查元素是否是字典,如果是,則使用遞歸更新。 如果它能夠轉換為浮點數或整數,則將其轉換並修改字典中的值。 沒有內置函數,它可能非常丑陋(並且非pythonic,因為它通常需要調用isinstance)。
對於蟒蛇 3,
for d in list:
d.update((k, float(v)) for k, v in d.items())
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
如果您決定采用“就地”解決方案,您可以看看這個:
>>> 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}]
順便說一句,鍵順序沒有保留,因為這是標准詞典的工作方式,即沒有順序的概念。
為了處理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}]
然而,直到 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}]
請注意,無論哪種方式,這都會創建一個新的列表字典,而不是就地修改原始字典(這需要以不同的方式完成)。
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]
這將處理整數、浮點數和十六進制格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.