将字典值转换为整数

时间:2015-05-22 18:54:22

标签: python

我在将一些数字从字符串转换为整数时遇到问题。这是有问题的功能:

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

我尝试了什么:我已尝试在字符串列表中添加字典之前将其转换为字典,并且我已经获得了相同的结果。我也尝试过使用dict理解,但是当我稍后使用该值时,这似乎会引起问题。

非常感谢任何建议,谢谢。

2 个答案:

答案 0 :(得分:2)

您正在以错误的方式分配dictinary值。它应该是

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'

修改

如果您尝试将整数值分配给字典键,则必须在分配时完成,如

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

答案 1 :(得分:2)

因为您在{}周围添加了firstLine[2],所以它会成为一个集合。如果您删除了{},它应该有效。

同样如上述评论中所述,您实际上需要在将其转换为int后保存该值。只是打电话int(discountValues['UpperLimit1'])实际上不会保存号码。如果你希望你的字典有整数而不是字符串,请尝试像discountValues['UpperLimit1'] = int(firstLine[2])这样的东西。