2024-04-20 11:16:39 发布
网友
我有一个口述是-team={ludo:4,monopoly:5}
team={ludo:4,monopoly:5}
我怎样才能形成一个新的dict,它有一个名为board_games的键,值是另一个dict,它有一个键,上面的团队dict应该是-
board_games
new_team = { board_games : {junior:{ludo:4,monopoly:5}}}
基本上我是想做点像perlish的事-
new_team['board_games']['junior'] = team
基本问题是,在您要编写的代码中,尝试访问new_team['board_games'],而不首先给它赋值。dict不支持这一点。你知道吗
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:
defaultdict
import collections new_team = collections.defaultdict(dict) 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}}}
如果您想动态构造它,^{}就是您需要的:
>>> 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)创建所需密钥:
或者:
甚至:
2)使用
defaultdict
:我看不出问题所在:
如果您想动态构造它,^{} 就是您需要的:
相关问题 更多 >
编程相关推荐