繁体   English   中英

从python字典中删除值

[英]remove values from a python dict

我有这样的python字典:

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

您应该能够使用del语句删除字典项。 例如:

del dct['1']['1']['C']

我在这里在黑暗中拍摄,但是您可能可以通过几种不同的方式进行拍摄。 一种方法是计算值,然后在将其粘贴到字典中之前确定是否要保留它。

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM