无损添加或合并Python字典
我正在尝试计算在两台服务器上的日志文件中找到的 IP 地址,然后将字典统计信息合并在一起,而不会丢失元素或计数。我在另一个堆栈溢出问题中找到了部分解决方案,但正如您所看到的,它删除了 '10.10.0.1':7
对。
>>> a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}
>>> b = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}
>>> c = {}
>>> for elem in a:
... c[elem] = b.get(elem, 0) + a[elem]
...
>>> print c
{'55.55.55.55': 10, '12.12.12.12': 5, '127.0.0.1': 6, '192.168.1.21': 50}
计数被添加到一起,但是如果字典 a 中不存在该键,则会将其删除。我无法弄清楚最后一点逻辑...也许是 b 中的 elem 的另一个:如果 a.get(elem, 0) 存在:传递 else 将其添加到 c?
I'm trying to count up ip addresses found in a log file on two servers and then merge the dictionary stats together without loosing elements or counts. I found a partial solution in another stack overflow question but as you can see it drops the '10.10.0.1':7
pair.
>>> a = {'192.168.1.21':23,'127.0.0.1':5,'12.12.12.12':5,'55.55.55.55':10}
>>> b = {'192.168.1.21':27,'10.10.0.1':7,'127.0.0.1':1}
>>> c = {}
>>> for elem in a:
... c[elem] = b.get(elem, 0) + a[elem]
...
>>> print c
{'55.55.55.55': 10, '12.12.12.12': 5, '127.0.0.1': 6, '192.168.1.21': 50}
The counts are being added together but if the key doesn't exist in dict a, it gets dropped. I'm having trouble figuring out the last bit of logic... perhaps another for elem in b: if a.get(elem, 0) exists: pass else add it to c?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在您的代码中,将
c = {}
替换为c = b.copy()
In your code replace
c = {}
withc = b.copy()
如果您使用的是 Python 2.7+,请尝试 collections.Counter
否则请尝试以下操作:
If you have Python 2.7+, try collections.Counter
Otherwise try the following:
怎么样:
How about:
如果我明白的话,这应该是对你的问题的一个非常通用的答案。
输出:
This should be a pretty generic answer to your question, if I got it.
Output:
python 2.6及更高版本的解决方案:
Solution for python 2.6 and higher: