将输入放入字典时将输入更改为int

时间:2013-02-26 23:52:47

标签: python csv converter

有没有办法在读入这个字典时将每个键值的值转换为int?最初他们是字符串但我更喜欢他们是整数。这是我尝试但我得到错误!每个键看起来像{'USA':('123,123','312,321,321')}但我希望这些数字是整数

**def _demo_fileopenbox():        
msg  = "Pick A File!"
msg2 = "Select a country to learn more about!"
title = "Open files"
default="*.py"
f = fileopenbox(msg,title,default=default)
writeln("You chose to open file: %s" % f)

countries = {}

with open(f,'r') as handle:
    reader = csv.reader(handle, delimiter = '\t')  
    for row in reader:
        countries[row[0]] = ((int(row[1])),(int(row[2])))
    while 1:
        reply = choicebox(msg=msg2, choices= list(countries.keys()) )
        writeln(reply + ";\tArea: " + (countries[reply])[0] + "\tPopulation: " + (countries[reply])[1] )
  **

谢谢!

2 个答案:

答案 0 :(得分:2)

尝试从字符串中删除逗号,然后再将其转换为int s:

countries[row[0]] = (int(row[1].replace(',', '')), int(row[2].replace(',', '')))

答案 1 :(得分:0)

您的问题是您的号码包含逗号。将代码更改为:

for row in reader:
    countries[row[0]] = tuple(int(a.replace(",","")) for a in row[1:])