我有一个字典是-team={ludo:4,monopoly:5}
我怎样才能形成一个新的字典,它有一个名为board_games
value 的键有另一个字典,它有一个键,上面的团队字典应该看起来像 -
new_team = { board_games : {junior:{ludo:4,monopoly:5}}}
基本上我正在尝试做一些类似 perlish 的事情 -
new_team['board_games']['junior'] = team
我有一个字典是-team={ludo:4,monopoly:5}
我怎样才能形成一个新的字典,它有一个名为board_games
value 的键有另一个字典,它有一个键,上面的团队字典应该看起来像 -
new_team = { board_games : {junior:{ludo:4,monopoly:5}}}
基本上我正在尝试做一些类似 perlish 的事情 -
new_team['board_games']['junior'] = team
我看不到问题:
>>> 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}}})
基本问题是,在您要编写的代码中尝试访问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