self.W = {}
self.W[A] = {'x':[], 'y':[]}
我想做以下事情:
self.W[A]['x'].append(X)
和:
self.W[A]['y'].append(Y),
立刻。
如何在一个命令中同时执行这两项操作?
编辑:
让我用一种更清晰的方式来写:
WEAPONS = {}
WEAPONS['launcher'] = {'idle_img' : [ "pic1.png", "pic2.png", "pic3.png"],
'shoot_img' : ['img1.png', 'img2.png', 'img3.png'],
WEAPONS['pistol'] = {'idle_img' : [ "another_pic1.png", "another_pic2.png",'another_pic3'],
'shoot_img' : ['another_img1.png', 'you know.png', 'abcxyz.png']}
现在我有了另一个dict
:
self.another_dict = {}
self.another_dict['launcher'] = {'idle_img' : [],
'shoot_img' : [],
self.another_dict['pistol'] = {'idle_img' : [],
'shoot_img' : []}
现在,我想把WEAPONS['pistol']['idle_img']
中的那些图像添加到self.another_dict['pistol']['idle_img']
中
也可以用['soot_img'](还有很多类似的['something_img'](。我可以一个接一个地做:
for l in WEAPONS:
for i in self.WEAPONS[l]['idle_img']:
self.another_dict[l]['idle_img'].append(i)
但如果我这样做的话,那就太长了
所以,我认为必须有一种方法可以同时完成,否则会有很多写作。
我想您可能会发现dict().from_keys()
很有帮助。
W = {}.fromkeys(['x', 'y'], [])
W['x'].append('hello')
{'x': ['hello'], 'y': ['hello']}
它使用提供的键创建一个字典,它们的默认值是同一个对象(如果可变的话(。因此,附加一个将附加另一个。但要小心,它们确实指向同一个对象,所以你将来必须采取额外的步骤来分别处理它们。
该死,我简直不敢相信我用了两次循环,但再也不用了。以下是我解决问题的方法:
for l in WEAPONS:
for t in self.another_dict[l]
for i in self.WEAPONS[l][t]:
self.another_dict[l][t].append(i)
所有答案的thx