开发者

remove values from a python dict

开发者 https://www.devze.com 2023-04-01 03:10 出处:网络
I had a python dict like this: {\'1\' : {\'1\': {\'A\' : 34, \'B\' : 23, \'C\' : nan, \'D\': 开发者_运维技巧inf, ...} ....} ....}

I had a python dict like this:

{'1' : {'1': {'A' : 34, 'B' : 23, 'C' : nan, 'D': 开发者_运维技巧inf, ...} ....} ....}

For each "letter" key I had to calculate something, but I obtained values like inf or nan and I need to remove them. How could I do that?

My first tried was to "cut" such values, i.e., to return just values between 0 and 1000 but when I did this, I got a dict with empty values:

{'1' : {'1': {'A' : 34, 'B' : 23, 'C' : {}, 'D': {}, ...} ....} ....}

perhaps there is a better solution, please help!!!!

This is part of my code, (Q and L are other dict that have the info that I need to calculate):

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


You should be able to use the del statement to delete the dictionary item. For example:

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


I'm taking a shot in the dark here, but you can probably do it in a couple of different ways. One method would be to calculate the value and then decide whether or not you actually want to keep it before sticking it into the dictionary.

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

I'm simplifying the dictionary to only pay attention to the part of your data that actually uses letters as keys since you haven't really given any context. That being said, I'd probably go with the first suggestion unless there's a reason not to.

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]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号