Python:基于匹配插入字典中的列表
我目前正在尝试将值插入一个列表,该列表通过首先识别匹配项打包到字典中。如果我有这样一本词典:Python:基于匹配插入字典中的列表,python,loops,dictionary,insert,indexing,Python,Loops,Dictionary,Insert,Indexing,我目前正在尝试将值插入一个列表,该列表通过首先识别匹配项打包到字典中。如果我有这样一本词典: {'12633': ['11-Mar-11', '26-Apr-11'], '11359': [], '11458': ['6-Aug-10'], '16335': ['29-May-13'], '11101': []} 我目前正在尝试的是逐行读取一个文件,并确定我的字典中是否存在密钥。然后确定该值是否匹配或存在于字典键返回的列表中。此时,我想在列表中匹配值旁边的行中插入一个值 with open('
{'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*
非常感谢你。你的解决方案非常有效,我真的很喜欢它,它能显著地分解它。我有一种感觉,在迭代列表时修改列表是个问题,但不确定在哪里修复它。再次感谢你。