如何在python中将dict作为值添加到键

2024-04-20 11:16:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个口述是-team={ludo:4,monopoly:5}

我怎样才能形成一个新的dict,它有一个名为board_games的键,值是另一个dict,它有一个键,上面的团队dict应该是-

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

基本上我是想做点像perlish的事-

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

Tags: boardnew团队dictgamesteam口述monopoly
2条回答

基本问题是,在您要编写的代码中,尝试访问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

我看不出问题所在:

>>> 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}}})

相关问题 更多 >