当前位置: 代码迷 >> python >> 将数据追加到字典中
  详细解决方案

将数据追加到字典中

热度:84   发布时间:2023-07-14 09:52:13.0

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

     Arjun   10th  20     88+

      +       77   76      36           

如何将class用作键并将其他值添加到相应的key。这看起来像{'10th':['20',[88,77,76,36]]}

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

尽管这个问题没有得到很好的解释,但我想您尝试做的是这样的事情。 请检查功能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)
  相关解决方案