从 python 字典中删除值
我有一个像这样的 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够使用 del 语句来删除字典物品。例如:
You should be able to use the del statement to delete the dictionary item. For example:
我在这里尝试一下,但你可能可以通过几种不同的方式来做到这一点。一种方法是计算该值,然后在将其放入字典之前决定是否确实要保留它。
我正在简化字典,只关注实际使用字母作为键的数据部分,因为您没有真正给出任何上下文。话虽这么说,我可能会接受第一个建议,除非有理由不这样做。
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.
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.