2015-05-22 98 views
1

我遇到問題,將一些數字從字符串轉換爲整數。這是有問題的功能:將字典值轉換爲整數

def read_discounts(): 
    myFile = open('discount.txt', 'r') 
    discountValues = {} 

    #read and split first line 
    firstLine = myFile.readline() 
    firstLine = re.sub(r'\$','',firstLine) 
    firstLine = re.sub(r'\%','',firstLine) 
    firstLine = firstLine.split() 

    #add values to dictionary 
    discountValues['UpperLimit1'] = {firstLine[2]} 
    int(discountValues['UpperLimit1']) 
    discountValues['PercentDiscount1'] = {firstLine[4]} 

而且回溯:

Traceback (most recent call last): 
File "C:\Users\Sam\Desktop\test.py", line 94, in <module> 
main() 
File "C:\Users\Sam\Desktop\test.py", line 6, in main 
discounts = read_discounts() 
File "C:\Users\Sam\Desktop\test.py", line 33, in read_discounts 
int(discountValues['UpperLimit1']) 
TypeError: int() argument must be a string or a number, not 'set' 

我稍微超出我的深度,但我知道,discountValues['UpperLimit']是應該能夠被轉換爲一個值整數(100

我試過了:我已經嘗試將字符串列表中的值轉換爲字典之前的值,並且我得到了相同的結果。我也嘗試過使用詞典理解,但是當我稍後使用該值時似乎會導致問題。

任何意見將不勝感激,謝謝。

+0

取出圍繞第一行的{和} [] – NendoTaka

+3

將錯誤整理出來後,可能值得注意的是int(discountValues ['UpperLimit1'])'沒有任何作用。 'int(somevalue)'不會將'somevalue'轉換爲int中的int值;你需要'somevalue = int(somevalue)'。 – Kevin

+0

謝謝都。特別是凱文,真的救了我。 – c3066521

回答

2

您正在以錯誤的方式分配字典值。它應該是

discountValues['UpperLimit1'] = firstLine[2] # Droped the { and } from assignment 
int(discountValues['UpperLimit1']) 
discountValues['PercentDiscount1'] = firstLine[4] 

包木窗了事情{}將創建sets in python3

測試

>>> a_dict = {} 
>>> a_dict["set"] = {"1"} # creates a set and assign it to a_dict["set"] 
>>> type(a_dict["set"]) 
<class 'set'> 
>>> a_dict["string"] = "1" # Here a string value is assigned to a_dict["string"] 

>>> type(a_dict["string"]) 
<class 'str'> 

>>> int(a_dict["string"]) 
1 
>>> int(a_dict["set"]) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: int() argument must be a string, a bytes-like object or a number, not 'set' 

編輯

如果你想整數值分配給字典鍵,它必須在轉讓時間,因爲你加在你firstLine[2]它使一組{}做過類似

discountValues['UpperLimit1'] = int(firstLine[2]) # int() converts string to int 
discountValues['PercentDiscount1'] = int(firstLine[4]) 
+0

如果downvoter會指出答案的錯誤,那將非常有幫助。謝謝 – nu11p01n73R

+0

感謝您的回覆。我糾正了字典值的分配。現在沒有錯誤,但字典值似乎仍然是一個字符串。任何想法我在這裏做錯了嗎? – c3066521

+0

這是因爲你只說'int(discountValues ['UpperLimit1'])'而不是'discountValues ['UpperLimit1'] = int(discountValues ['UpperLimit1'])''。 int()調用返回一個值 - 它不會原地修改傳遞的對象。 – TigerhawkT3

2

。如果你刪除{}它應該工作。

同樣如上述註釋之一,您實際上需要在將其保存爲int後保存該值。只需撥打int(discountValues['UpperLimit1'])就不會實際保存號碼。如果你想讓你的字典有整數而不是字符串,試試類似discountValues['UpperLimit1'] = int(firstLine[2])