【问题标题】:Python - Creating a dictionary from external text filePython - 从外部文本文件创建字典
【发布时间】:2013-07-13 05:44:04
【问题描述】:

所以我的文件看起来像这样:

0 1
0 2
0 34
0 67
1 98
1 67
1 87
2 23
2 45
2 98
...

等等。我的问题是,我怎样才能从这个文本文件中制作一个看起来像这样的字典:

dict = {'0':['1', '2', '34', '67']
        '1':['98', '67', '87']
        '2':['23', '45', '98']
        '3':['x','x','x']}

【问题讨论】:

  • 不要使用dict 作为变量名,因为它是一个内置类型。请改用Dict
  • @PeterVaro 使用dict 很糟糕,你是对的。但是Dict 也好不到哪里去;它的意思是一个类。
  • @glglgl 你是对的,如果我命名一个参数,我总是使用dictionaryd,如果我将它用作“普通”变量,则使用一个详细的名称。虽然使用 CapitalCaseWords for classes 只不过是一个约定而已。不错,我不得不说,但不是规则!

标签: python file dictionary


【解决方案1】:
from collections import defaultdict
res = defaultdict(list)
with open(file) as f:
    for line in f:
        temp = line.split()
        res[temp[0]].append(temp[1])

【讨论】:

  • line.strip().split() 仅相当于 line.split(),只是后者更快且更具可读性。
【解决方案2】:

一个非常有趣且优雅的解决方案:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> with open(external_file) as f:
    map(lambda x: d[x[0]].append(x[1]), map(str.split, f))
>>> d
defaultdict(<type 'list'>, {'1': ['98', '67', '87'], '0': ['1', '2', '34', '67'], '2': ['23', '45', '98']})

【讨论】:

    【解决方案3】:

    假设文件名为test.txt

    from collections import defaultdict
    import csv
    
    
    data = defaultdict(list)
    with open("test.txt", "r") as f:
        reader = csv.reader(f, delimiter=" ")
        for row in reader:
            data[row[0]].append(row[1])
    

    那么data 的值将是:

    {
     '0': ['1', '2', '34', '67'], 
     '1': ['98', '67', '87'], 
     '2': ['23', '45', '98'],
     ...
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-07
      • 2012-03-08
      • 1970-01-01
      • 2012-04-10
      • 2018-03-29
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多