我有一个 csv 文件,它包含
a,b
2,3
4,5
4,7
4,7
(其中 a,b 是列值( 下面我有两个函数,第一个函数将读取 csv 并将"a"作为键,将"b"作为字典中的值
第二个函数 i 将传递"a"值作为参数,当我使用该函数时,它会返回 b 作为值。如果"a"没有值,我得到 None。
def x (id):
dict1= {}
with open(file, 'r', encoding='utf') as f:
for i in csv.DictReader(f, skipinitialspace= True)
dict1[i['a']] = row['b']
print('im happy now' )
def getx (a):
return dict1.get(a, None)
它工作得很好。
现在我有一个包含四个列值的 csv 文件
a,b,c,d
1,2,r,4
2,g,4,6
3,d,4,6
为此,我写了一段代码,例如
def x ():
dict1= {}
with open(file, 'r', encoding='utf') as f:
for i in csv.DictReader(f, skipinitialspace= True)
dict1[i['a']] = dict(dict1[i['b']] = dict(dict1[i['c']] = row['d']))
print('im happy now' )
def getx (a):
return dict1.get(dict1['a']['b']['c'], None)
我的逻辑是展示
dict1[i['a']] = dict(dict1[i['b']] = dict(dict1[i['c']] = row['d']))
如
dict1 :{
'a':{
'b':{
'c':2,
'c':4,
'c':4
}
}
}
我不确定我上面写的是否正确。
当我传递dict1[a[]b][c]时,我需要返回'd'作为值。它返回我空值。
期望值是对于 a,b,c 的组合,我需要一个值作为 d。
例如:从上面的csv。对于 1,2,r 的组合,我需要返回 4 作为输出
更新:
我意识到"a"列具有重复的值,并且无法在跳过重复键记录的字典键中处理。
from collections import defaultdict
dict_1 = defaultdict(list)
with open('file.txt','r') as f:
for r in f.readline():
i= r['a']
j= r['b']
k= r['c']
l =r['d']
details = [j,k,l]
dict_1[i].append((details))
print(dict_1)
这给了我
{'1' :[('k', '3', '5'),('e','3','2')], '4' :[('r','3','2'),('e','2','1')],....................}
如果我在上面的第一个函数中有dict_1。 现在,任何建议,例如如何通过在第二个函数中传递 a,b,c 作为参数来获取"d"的值,否则没有?
你不需要csv模块。此外,字典中不能有重复的键,只会覆盖以前设置的值。
def x():
dict1= {}
with open(file, 'r', encoding='utf') as f:
for i in f.readlines():
a, b, c, d = i.split(',')
dict1[a] = {b: {c: d}}
def getx(a, b, c):
try:
return dict1[a][b][c]
except:
return None