Python:根据匹配插入字典中的列表

标签 python loops dictionary insert indexing

我目前正在尝试将值插入到列表中,该列表通过首先识别匹配项打包到字典中。如果我有这样的字典:

{'12633': ['11-Mar-11', '26-Apr-11'], '11359': [], '11458': ['6-Aug-10'], '16335': ['29-May-13'], '11101': []}

我目前正在尝试做的是逐行读取文件并确定该键是否存在于我的字典中。然后确定该值是否匹配或存在于字典键返回的列表中。此时,我想从列表中匹配值旁边的行中插入一个值。

with open('Pfa.csv', 'r') as f:
    for line in f:
        #split the line up into individual element - it's a csv file
        line = line.strip('/n')
        splitline = line.split(',')
        #check if the value in the file exists as a key in the dictionary
        if splitline[0] in Ndates:
            #iterate over the list in the dictionary
            for item in Ndates[splitline[0]]:
                #check if the item within the dictionary list is within this line in the file
                if item == splitline[1]:
                    #insert a vale from the file next to the value in the list within the dictionary
                    Ndates[splitline[0]].insert(Ndates[splitline[0]].index(item), splitline[4].strip('\n'))

不幸的是,由于某种我无法确定的原因,它似乎卡在循环数据中。只需将值附加到列表就可以了,但是它很困惑并且有将近 3k 个值,我不想手动完成。

非常感谢任何帮助让我知道我要去哪里错了。我觉得我这样做效率很低,但我愿意学习。

最佳答案

您在迭代列表时正在修改它。

一个修复:

        #iterate over the list in the dictionary
        for item in Ndates[splitline[0]][:]:

这会在迭代之前复制列表。

但我建议重构:

import csv

with open('Pfa.csv') as f: #'r' is default
    for row in csv.reader(f):
        key = row[0]
        try:
            values = Ndates[key]
            i = values.index(row[1])
        except (KeyError, ValueError):
            pass
        else:
            values.insert(i, row[4]) #this will insert *before* the match; use i + 1 insert *after*

关于Python:根据匹配插入字典中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21275716/

相关文章:

jquery - 如何在 PhantomJS 中使用 jQuery 循环表行

c++ - 配置解析器打印空白

python - 如何在 Python 中读取 Excel 格式的日期?

python - django createsuperuser 不工作

python - 写 csv 头从下面写的 numpy 数组中删除数据

python - python 中是否有任何可哈希的内置对象是可变的?

C# 遍历按值排序的字典

python - 在 Ubuntu 中从 RCCC Bayer 相机传感器读取图像流

javascript - jquery 未捕获语法错误 : Illegal break statement

java - 此代码的问题(抱歉,我不能具体说明)