【问题标题】:How can I get the contents of a file in dictionary using python?如何使用 python 获取字典中文件的内容?
【发布时间】:2021-02-18 14:54:13
【问题描述】:

我有一个文件,其内容如下。它代表两个路口及其重量或距离。

a / b / 3
a / c / 5
a / d / 2
b / a / 3
b / e / 11
b / f / 12
c / a / 5
c / f / 7
d / a / 2
d / f / 8
d / g / 5
e / b / 11
e / f / 3
e / h / 3
f / b / 12
f / c / 7
f / d / 8
f / e / 3
f / g / 4
f / h / 7
f / i / 5
f / k / 4
g / d / 5
g / f / 4
g / k / 5
h / e / 3
h / f / 7
h / j / 2
i / f / 5
i / j / 3
j / h / 2
j / i / 3
j / k / 6
k / g / 5
k / f / 4
k / j / 6

我想从文件中创建一个字典,或者更确切地说是一个图表,如下所示:

graph = {'a':{'b':3,'c':5,'d':2},'b':{'a':3,'e':11,'f':12},'c':{'a':5,'f':7},'d':{'a':2,'f':8,'g':5},'e':{'b':11,'f':3,'h':3},'f':{'b':12,'c':7,'d':8,'e':3,'g':4,'h':7,'i':5,'k':4},'g':{'d':5,'f':4,'k':5},'h':{'e':3,'f':7,'j':2},'i':{'f':5,'j':3} ,  'j':{'h':2,'i':3,'k':6}  ,'k':{'g':5,'f':4,'j':6}      }  
    

【问题讨论】:

    标签: python file dictionary graph


    【解决方案1】:

    逐行读取文件,替换冗余空间,并准备所需的字典,其中包含所需的键和值:

    res = dict()
    with open('inp.txt', 'r') as f:
        for line in f:
            line = line.replace(" ", "").rstrip()
            lst = line.split('/')
            
            if lst[0] in res.keys():
                res[lst[0]].update({lst[1]: int(lst[2])})
            else:
                res[lst[0]] = {lst[1]: int(lst[2])}
            
    print(res)
    

    输出:

    {'a': {'b': 3, 'c': 5, 'd': 2}, 'b': {'a': 3, 'e': 11, 'f': 12}, 'c': {'a': 5, 'f': 7}, 'd': {'a': 2, 'f': 8, 'g': 5}, 'e': {'b': 11, 'f': 3, 'h': 3}, 'f': {'b': 12, 'c': 7}}
    

    注意:为简洁起见,我只取了一部分数据。

    【讨论】:

      【解决方案2】:

      您可以逐行解析文件,在/ 上拆分并添加到名为graph 的字典中。这里的关键是创建一个defaultdict 对象来保存数据以避免KeyError。我会这样做:

      #!/usr/bin/env python
      import sys
      from collections import defaultdict
      
      input_file = sys.argv[1]
      
      graph = defaultdict(dict)
      
      with open(input_file) as fh:
          for line in fh:
              elems = line.rstrip('\n').split(' / ')
              graph[elems[0]].update({elems[1] : int(elems[2])})
      

      这将导致:

      {'a': {'b': '3', 'c': '5', 'd': '2'},
       'b': {'a': '3', 'e': '11', 'f': '12'},
       'c': {'a': '5', 'f': '7'},
       'd': {'a': '2', 'f': '8', 'g': '5'},
       'e': {'b': '11', 'f': '3', 'h': '3'},
       'f': {'b': '12',
             'c': '7',
             'd': '8',
             'e': '3',
             'g': '4',
             'h': '7',
             'i': '5',
             'k': '4'},
       'g': {'d': '5', 'f': '4', 'k': '5'},
       'h': {'e': '3', 'f': '7', 'j': '2'},
       'i': {'f': '5', 'j': '3'},
       'j': {'h': '2', 'i': '3', 'k': '6'},
       'k': {'f': '4', 'g': '5', 'j': '6'}}
      

      【讨论】:

      • 感谢您的回复。那么,数字将被视为字符串吗?我们如何将它们视为整数。
      • 您可以使用int() 方法将它们转换为整数。我更新了代码以将数字设置为整数而不是字符串。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 2011-10-28
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      相关资源
      最近更新 更多