从Python字典中删除值

0 投票
2 回答
2874 浏览
提问于 2025-04-17 01:07

我有一个这样的 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

2 个回答

1

你可以使用 del 这个语句来删除字典中的某个项目。比如说:

del dct['1']['1']['C']
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]

撰写回答