【问题标题】:How to create a dictionary from a file in python如何从python中的文件创建字典
【发布时间】:2012-12-01 18:55:05
【问题描述】:

我有一个这样的文件:

group #1
a b c d
e f g h

group #2
1 2 3 4
5 6 7 8

我怎样才能把它变成这样的字典:

{'group #1' : [[a, b, c, d], [e, f, g, h]], 
 'group #2' :[[1, 2, 3, 4], [5, 6, 7, 8]]}

【问题讨论】:

  • 到目前为止,您尝试了什么?什么没用,什么没用,你现在在挣扎什么?

标签: python file dictionary


【解决方案1】:
file = open("file","r")                       # Open file for reading 
dic = {}                                      # Create empty dic

for line in file:                             # Loop over all lines in the file
        if line.strip() == '':                # If the line is blank
            continue                          # Skip the blank line
        elif line.startswith("group"):        # Else if line starts with group
            key = line.strip()                # Strip whitespace and save key
            dic[key] = []                     # Initialize empty list
        else:
            dic[key].append(line.split())     # Not key so append values

print dic

输出:

{'group #2': [['1', '2', '3', '4'], ['5', '6', '7', '8']], 
 'group #1': [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']]}

【讨论】:

  • 您可能希望 dic[key].append(..) 中的 line.split() 与 OP 想要的匹配。
  • NP。我喜欢所有的cmets! :-)
  • 这里对空行的检查是多余的。
  • @BurhanKhalid 不是这样,您最终会为每个空行添加一个额外的空列表。
  • line.strip().split() 虽然是多余的:)。和line.split()一模一样。
【解决方案2】:

遍历文件,直到找到“组”标签。使用该标签将新列表添加到您的字典中。然后将行附加到该标签,直到您点击另一个“组”标签。

未经测试

d = {}
for line in fileobject:
    if line.startswith('group'):
        current = d[line.strip()] = []
    elif line.strip() and d:
        current.append(line.split())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多