将数据附加到字典中

时间:2014-03-14 08:25:13

标签: python list dictionary

我正在阅读file.txt,其中包含以下数据:

     Arjun   10th  20     88+

      +       77   76      36           

如何将类作为键并将其他值添加到相应的键中。它将如下所示 {'10th':['20',[88,77,76,36]]}

注意:行中的值以+符号结尾,下一行以+号开头,我们如何将它们插入到同一列表中?

1 个答案:

答案 0 :(得分:0)

尽管问题没有得到很好的解释,但我认为你尝试做的事情是这样的。请检查函数words并告诉我这是否正好在正确的方向上。

def words(d, auxList):
    # Variables to save state between lines
    curKey = None
    values = []

    for line in auxList:
        items = line.split()
        # Check if we have values already from a previous line
        if curKey is None:
            # Check if we see a continuation symbol (+)
            if items[-1][-1] == '+':
                # and remove it from the value
                items[-1] = items[-1][:-1]
                # Save the info in this line
                curKey = items[1]
                values = items[2:]
            else:
                # If all the information is in one simple line
                d[items[1]] = items[2:]
        else:
            # Check if we see a continuation symbol (+)
            if items[-1][-1] == '+':
                # and remove it from the value
                items[-1] = items[-1][:-2]
                # Save the info in this line and accumulate it
                # with the previous ones
                values.extend(items[1:])
            else:
                # Update dictionary when we have all the values
                d[curKey] = values + items[1:]
                # and reset state
                curKey = None
                values = []

    # Be sure to save the last line if there is no more info
    # Maybe it is not necessary
    if curKey is not None:
        d[curKey] = values


d = {}
a2 = [line.strip() for line in myfile.readlines()]
words(d, a2)