如何将一个dict作为值添加到python中的键

时间:2013-09-07 20:19:25

标签: python dictionary

我的词典是 - team={ludo:4,monopoly:5}

我如何形成一个新的dict,其中有一个名为board_games的键具有值,另一个dict具有上面团队所指的键,应该是 -

new_team = { board_games : {junior:{ludo:4,monopoly:5}}}

基本上我正在尝试做一些像perlish一样的事情 -

new_team['board_games']['junior'] = team

2 个答案:

答案 0 :(得分:3)

我没有看到问题:

>>> team = {"ludo": 4, "monopoly": 5}
>>> new_team = {"board_games": {"junior": team}}
>>> new_team
{'board_games': {'junior': {'ludo': 4, 'monopoly': 5}}}

如果您想动态构建它,collections.defaultdict就是您所需要的:

>>> from collections import defaultdict
>>> new_dict = defaultdict(dict)
>>> new_dict['board_games']['junior'] = team
>>> new_dict
defaultdict(<type 'dict'>, {'board_games': {'junior': {'ludo': 4, 'monopoly': 5}}})

答案 1 :(得分:1)

基本问题是,在您要编写的代码中,尝试访问new_team['board_games']而不先为其分配任何值。 dict不支持。

如果你绝对坚持要写new_team['board_games']['junior'] = team,那么有两种方法:

1)创建您需要的密钥:

new_team = { 'board_games' : dict() }
new_team['board_games']['junior'] = team

或者也许:

new_team = dict()
new_team['board_games'] = dict()
new_team['board_games']['junior'] = team

甚至:

new_team = dict();
new_team.setdefault('board_games', dict())
new_team['board_games']['junior'] = team

2)使用defaultdict

import collections
new_team = collections.defaultdict(dict)
new_team['board_games']['junior'] = team