【问题标题】:python conversion to integer in a dictionarypython转换为字典中的整数
【发布时间】:2014-04-10 15:55:30
【问题描述】:

如何将{'CS2261': '140', 'CS3264': '55'} 转换为{'CS2261': 140, 'CS3264': 55}

def everything(file):
    a = {}
    with open(file, 'r') as f:
        for i in f:
            Module,Group,Quota = i.split(',')
            if Module not in a:
                a[Module] = int(Quota)
        return a

【问题讨论】:

  • 您正在询问转换 字典,但随后发布了构建 字典的代码示例。 everything() 函数的确切问题是什么,它与第一句话的关系是什么?

标签: python dictionary int


【解决方案1】:

你可以像这样用字典理解重构字典

d = {'CS2261': '140', 'CS3264': '55'}
print {k: int(d[k]) for k in d}
# {'CS3264': 55, 'CS2261': 140}

【讨论】:

  • 为不使用k,v in d.items()(+1)而羞愧地低下头
  • @inspectorG4dget 在 Python 2.7 中,它必须创建另一个列表。所以,我不喜欢这样:)
  • 很好,d.iteritems(),然后
  • @inspectorG4dget 它在 Python 3.x 中不起作用 :)
  • 很好,如果你想要向后移植
【解决方案2】:
{k:int(v) for k,v in d.items()}

【讨论】:

  • 或者对于python 2中的大型字典,.iteritems()
猜你喜欢
  • 2018-07-15
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多