【问题标题】:Put two strings into a key and the rest into value from multiple lines in file将两个字符串放入一个键中,将其余字符串放入文件中多行的值中
【发布时间】:2019-11-16 19:29:19
【问题描述】:

我的文件是这样的:

House Plant, 2, 5, 6
House Plant1, 4, 5, 7
... and so on

我希望这两个词作为键,数字作为整数值,并将所有行放入字典中。

{'House Plant':[2,5,6],'House Plant1':[4,5,7], etc}

这并不是真的这样工作:

dictionary = {}

with open("persons.dat","r") as file:
    for line in file:
        items = line.split()
        key, values = items[1], items[2:]
        dictionary.setdefault(key,[]).extend(values)
    print(items)

【问题讨论】:

    标签: python file dictionary


    【解决方案1】:

    首先,您必须根据, 拆分行。

    items = line.split(',')
    

    另外,collections.defaultdict 是管理 list 项目的更好选择。

    from collections import defaultdict
    dictionary = defaultdict(list)
    
    with open("persons.dat","r") as file:
        for line in file:
            items = line.split(',')
            key, values = items[0], items[1:]
            dictionary[key].extend(list(map(int, values)))
    

    【讨论】:

      【解决方案2】:

      首先使用',' 分割你的字符串:

      dictionary = {}
      
      with open("persons.dat", "r") as file:
          for line in file:
              items = line.split(',')
              dictionary[items[0]] = [int(x) for x in items[1:]]
      
      print(dictionary)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-26
        • 2019-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-06
        • 1970-01-01
        • 2013-03-04
        相关资源
        最近更新 更多