【问题标题】:Appending Elements to a Dictionary from a text file and Setting them to None [Python]将元素从文本文件附加到字典并将它们设置为无 [Python]
【发布时间】:2020-06-21 12:04:45
【问题描述】:

我想从文本文件中追加字符串(逐行),然后将这些字符串设置为 None 值。有没有办法将这些值中的每一个都默认为无?

即 文本文件:

Hello
World

字典:

{"Hello":None, "World":None}

【问题讨论】:

    标签: python python-3.x data-structures


    【解决方案1】:

    不知道你为什么想要一本Nones....

    Dictionary={}
    
    with open(FILE, "rt") as f:
        for line in f.readlines():
            Dictionary[line.strip()]=None
    

    【讨论】:

      【解决方案2】:

      @KJTHoward 的回答效果很好。如果您愿意,还有一个内置方法可以做到这一点,称为dict.fromkeys()。见that answer

      with open("path/to/file", "r") as f:
          my_dict = dict.fromkeys([line.strip() for line in f.readlines()])
      

      或者一个干净的 dict 理解方式:

      with open("path/to/file", "r") as f:
          my_dict = {key: None for key in [line.strip() for line in f.readlines()]}
      

      【讨论】:

        猜你喜欢
        • 2023-03-02
        • 1970-01-01
        • 2014-04-23
        • 2022-12-10
        • 2013-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多