我有一个像这样的python dict:
{'1' : {'1': {'A' : 34, 'B' : 23, 'C' : nan, 'D': inf, ...} ....} ....}
对于每个“字母”键,我必须计算一些东西,但我获得了像inf或nan这样的值,我需要删除它们。我怎么能这样做?
我的第一次尝试是“剪切”这样的值,即只返回0到1000之间的值,但是当我这样做时,我得到了一个空值的字典:
{'1' : {'1': {'A' : 34, 'B' : 23, 'C' : {}, 'D': {}, ...} ....} ....}
或许有更好的解决方案,请帮助!!!!
这是我的代码的一部分,(Q和L是其他包含我需要计算的信息的词典):
for e in L.keys():
dR[e] = {}
for i in L[e].keys():
dR[e][i] = {}
for l, ivalue in L[e][i].iteritems():
for j in Q[e].keys():
dR[e][i][j] = {}
for q, jvalue in Q[e][j].iteritems():
deltaR = DeltaR(ivalue, jvalue) #this is a function that I create previously
if (0 < deltaR < 100):
dR[e][i][j] = deltaR
答案 0 :(得分:1)
您应该能够使用del语句删除字典项。例如:
del dct['1']['1']['C']
答案 1 :(得分:0)
我在黑暗中拍摄,但你可以用几种不同的方式做到这一点。一种方法是计算该值,然后在将其粘贴到字典中之前确定是否确实要保留它。
d = {}
for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
# I don't actually know how you're calculating values
# and it kind of doesn't matter
value = calculate(letter)
if value in (inf, nan):
continue
d[letter] = value
我正在简化字典,只关注实际使用字母作为键的数据部分,因为你没有真正给出任何上下文。话虽这么说,我可能会提出第一个建议,除非有理由不这样做。
for e in L.keys():
dR[e] = {}
for i in L[e].keys():
dR[e][i] = {}
for l, ivalue in L[e][i].iteritems():
for j in Q[e].keys():
#dR[e][i][j] = {} # What's up with this? If you don't want an empty dict,
# just don't create one.
for q, jvalue in Q[e][j].iteritems():
deltaR = DeltaR(ivalue, jvalue) #this is a function that I create previously
if (0 < deltaR < 100):
dR[e][i][j] = deltaR
if dR[e][i][j] in (nan, inf):
del dR[e][i][j]