开发者

Removing redundancy when adding items to Python dictionaries

Suppose you have a dictionary like:

my_dict = {'foo' : {'bar' : {}}}

And you want to make the following sequence of 开发者_开发问答assignments:

my_dict['foo']['bar']['first'] = 1
my_dict['foo']['bar']['second'] = 2

Clearly there is some redundancy in the fact that my_dict['foo']['bar'] is repeated. Is there any way to prevent this redundancy?

Thanks!


Not really, save of course the obvious intermediate variable:

foo_bar = my_dict['foo']['bar']
foo_bar['first'] = 1
foo_bar['second'] = 2

How is Python supposed to know you want to refer to the same dictionary twice unless you tell it like this?


You could do:

my_dict['foo']['bar'].update({'first': 1, 'second': 2})


you could hold it in a temporary:

temp = my_dict['foo']['bar']
temp['first'] = 1
temp['second'] = 1

or you could use update:

my_dict['foo']['bar'].update([('first', 1), ('second', 2)])

or there are other options.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜