【问题标题】:Adding a value to a pre existing dictionary key when importing the data from a text file (Python 3)从文本文件导入数据时向预先存在的字典键添加值(Python 3)
【发布时间】:2017-09-09 19:21:40
【问题描述】:

我正在尝试通过从类似这样的文本文件中提取来创建字典,

Fred beats Amy  
Fred beats Tom  
Tom beats Amy   
Amy beats Jordan 

我现在正在使用

f = open("RockPaperScissors.txt", 'r')  
fwDict = {}  
for line in f:  
    k, v = line.strip().split('beats')  
    fwDict[k.strip()] = v.strip()  


f.close()

我遇到的问题是,当“Fred”多次出现时,它只会覆盖以前的值 (Amy) 并用最新的值 (Tom) 替换它,有什么办法可以添加一个新值如果密钥已经存在,即使从 txt 文件中提取?

谢谢!

【问题讨论】:

    标签: python python-3.x dictionary append


    【解决方案1】:

    您可以将字典的值替换为列表:

    f = open("RockPaperScissors.txt", 'r')  
    fwDict = {}  
    for line in f:  
        k, v = line.strip().split('beats')
    
        # If we already have the key in the dictionary, just append to the list
        if k.strip() in fwDict:
            fwDict[k.strip()].append(v.strip())
    
        # If we don't have the key in the dict, create the new key-value pair as a list
        else:
            fwDict[k.strip()] = [v.strip()]
    
    
    f.close()
    

    【讨论】:

      【解决方案2】:

      这是defaultdict 的一个很好的用例,它在访问键时会创建一个默认值。

      如果我们在这种情况下使用列表作为默认值,您的代码可以简化为以下内容:

      from collections import defaultdict
      
      fw_dict = defaultdict(list)
      
      with open('RockPaperScissors.txt', 'r') as f:
          for line in f:
              k, v = line.strip().split('beats')
              fw_dict[k.strip()].append(v.strip())
      

      这样您就可以根据需要获得每个键的结果值。

      注意with 行,它确保文件句柄在块的末尾关闭。您不必这样做,但它可以省去您以后必须执行 f.close() 的操作(或仅依靠进程关闭并放下句柄)。

      【讨论】:

      • 使用split(' beats '),你就不必strip k & v
      【解决方案3】:

      如果你想让元素不重复,你可以使用 set 代替 list:

      f = open("RockPaperScissors.txt", 'r')  
      fwDict = {}  
      for line in f:  
          k, v = line.strip().split('beats')
          if k.strip() in fwDict:
              fwDict[k.strip()].add(v.strip())
          else:
              a = set()
              a.add(v.strip())
              fwDict[k.strip()] = a
      
      
      f.close()
      

      或使用默认字典:

      from collections import defaultdict
      
      f = open("RockPaperScissors.txt", 'r')  
      fwDict = defaultdict(set)
      for line in f:  
          k, v = line.strip().split('beats')
          fwDict[k.strip()].add(v.strip())
      
      
      f.close()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-09
        • 1970-01-01
        • 2020-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多