我得到了这3个字典:
self.Update()
我做了一个新的决定:
import wx
class Mywin(wx.Frame):
def __init__(self, parent, title):
super(Mywin, self).__init__(parent, title=title, size=(500, 300))
self.InitUI()
def InitUI(self):
self.panel = wx.Panel(self)
self.panel.SetBackgroundColour(wx.Colour('RED'))
self.Centre()
self.Show(True)
menuBar = wx.MenuBar()
RectangleButton = wx.Menu()
Item1 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 1')
Item2 = RectangleButton.Append(wx.ID_ANY, 'Rectangle 2')
menuBar.Append(RectangleButton, 'Rectangles')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.DrawRect1, Item1)
self.Bind(wx.EVT_MENU, self.DrawRect2, Item2)
def DrawRect1(self, e):
self.panel.SetBackgroundColour(wx.Colour('BLUE'))
self.Refresh()
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(10, 10, 100, 100)
def DrawRect2(self, e):
self.panel.SetBackgroundColour(wx.Colour('GREEN'))
self.Refresh()
self.Update()
self.dc = wx.ClientDC(self.panel)
self.dc.SetBrush(wx.Brush(wx.Colour('white')))
self.dc.DrawRectangle(20, 20, 50, 50)
myApp = wx.App()
Mywin(None,'Drawing demo')
myApp.MainLoop()
然后我用:
d = {'x': 1, 'y': 2, 'z': 3}
e = {'x': 2, 'y': 3, 'z': 1}
f = {'t': 1, 'q': 2, 'n': 3}
我得到了:
new_dict = {}
但是我想得到:
new_dict.update(d)
new_dict.update(e)
new_dict.update(f)
换句话说,我不想每个键和值都覆盖它的前一个-我想对每个键的值求和。我该怎么办?
答案 0 :(得分:0)
使用collections.Counter
例如:
from collections import Counter
d = {'x': 1, 'y': 2, 'z': 3}
e = {'x': 2, 'y': 3, 'z': 1}
f = {'t': 1, 'q': 2, 'n': 3}
new_dict = Counter(d) + Counter(e) + Counter(f)
print(new_dict)
输出:
Counter({'y': 5, 'z': 4, 'n': 3, 'x': 3, 'q': 2, 't': 1})
答案 1 :(得分:0)
尝试:
from collections import Counter
d = {'x': 1, 'y': 2, 'z': 3}
e = {'x': 2, 'y': 3, 'z': 1}
f = {'t': 1, 'q': 2, 'n': 3}
l = [d,e,f]
new_dict = Counter()
for d in l:
new_dict.update(d)
您会得到:
Counter({'x': 3, 'y': 5, 'z': 4, 't': 1, 'q': 2, 'n': 3})
答案 2 :(得分:0)
您可以遍历每个字典并添加相同键的值,而不用创建3个Collections.Counter
实例
d = {'x': 1, 'y': 2, 'z': 3}
e = {'x': 2, 'y': 3, 'z': 1}
f = {'t': 1, 'q': 2, 'n': 3}
dct = {}
#Iterate over every dict
for l in [d, e, f]:
#Add up values for the same key
for k,v in l.items():
if k in dct:
dct[k] += v
else:
dct[k] = v
print(dct)
#{'x': 3, 'y': 5, 'z': 4, 't': 1, 'q': 2, 'n': 3}