ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-11-22 07:08:52  阅读:273  来源: 互联网

标签:dictionary loops indexing python insert


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

{'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*

标签:dictionary,loops,indexing,python,insert
来源: https://codeday.me/bug/20191122/2057973.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有