【问题标题】:How to read from a file into a dict with string key and tuple value?如何从文件中读取到带有字符串键和元组值的字典?
【发布时间】:2013-07-17 14:30:35
【问题描述】:

对于一项任务,我正在创建一个程序,该程序从文件中检索有关奥林匹克国家及其奖牌数量的信息。

我的一个函数通过这种格式的列表:

Country,Games,Gold,Silver,Bronze
AFG,13,0,0,2
ALG,15,5,2,8
ARG,40,18,24,28
ARM,10,1,2,9
ANZ,2,3,4,5

该函数需要遍历这个列表,并以国家名称为键存储到字典中,其余四个条目为元组。

这是我目前正在使用的:

def medals(string):
    '''takes a file, and gathers up the country codes and their medal counts
    storing them into a dictionary'''

    #creates an empty dictionary
    medalDict = {}
    #creates an empty tuple
    medalCount = ()
    #These following two lines remove the column headings
    with open(string) as fin:
        next(fin)

        for eachline in fin:
            code, medal_count = eachline.strip().split(',',1)
            medalDict[code] = medal_count

    return medalDict

现在,目的是让条目看起来像这样

{'AFG': (13, 0, 0, 2)}

相反,我得到了

{'AFG': '13,0,0,2'}

看起来它被存储为字符串,而不是元组。是不是跟

有关系
medalDict[code] = medal_count

代码行?我不太确定如何将其巧妙地转换为元组的单独整数值。

【问题讨论】:

    标签: python python-3.x dictionary tuples iterable-unpacking


    【解决方案1】:

    您将整个字符串 '13,0,0,2' 存储为值,所以

    medalDict[code] = medal_count
    

    应替换为:

    medalDict[code] = tuple(medal_count.split(','))
    

    您最初的想法是正确的,这一行是唯一的例外。改变的是现在它将 '13,0,0,2' 拆分为列表 ['13', '0', '0', '2'] 并将其转换为元组。

    你也可以这样做将里面的字符串转换成整数:

    medalDict[code] = tuple([int(ele) for ele in medal_count.split(',')])
    

    但请确保您的 Medal_count 仅包含整数。

    【讨论】:

      【解决方案2】:

      这一行:

      code, medal_count = eachline.strip().split(',',1)
      

      ... 是splitting 空格-stripped eachline, 1 时间,在',',然后将生成的两个字符串存储到codemedal_count ... 所以是的,medal_count 包含一个字符串。

      您可以通过以下两种方式之一处理:

      1. 沿以下行添加一行:

        split_counts = tuple(medal_count.split(','))
        

        ...然后在代码中使用split_counts,或者

      2. (在 Python 3 中)将上面的行更改为

        code, *medal_count = eachline.strip().split(',')
        

        ...它使用Extended iterable unpacking(并且会给你一个列表,所以如果需要一个元组,它就需要被转换)。

      【讨论】:

        【解决方案3】:

        您的问题似乎是这样的:

        split(',',1)
        # should be
        split(',')
        

        因为split(..., 1) 只进行1 次拆分,而split(...) 则尽可能进行拆分。

        所以你应该能够做到这一点:

            for eachline in fin:
                code, *medal_count = eachline.strip().split(',')
                medalDict[code] = medal_count
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-16
          • 2015-01-17
          • 1970-01-01
          • 2016-06-24
          • 1970-01-01
          • 2015-05-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多