如何在dict [python]中更新和访问dict的子键

时间:2013-01-07 11:03:16

标签: python python-2.7

我在dict中使用dict来计算与20个项目相关的四个参数。

resi = {'a': {'x': 0, 'y': 0, 'z': 0}, 'b': {'x': 0, 'y': 0, 'z': 0}, ...}

函数'count'计算20个项目出现的参数x,y,z的频率。

re:主要字典resi中的一个键; bas:嵌套字典中的一个键

def count(re, bas, aa = resi) :
    t = aa[re] 
    t[bas] += 1
    print aa

调用该函数时,count会更新所有主键中的参数。我也试过

aa[re][0][bas] += 1

这显示了一个关键错误。如何更新主字典中的特定键?

2 个答案:

答案 0 :(得分:2)

你首先创造了这个词。

resi = dict((k, {'x':0, ...}) for k in ('a', 'b', ...))

答案 1 :(得分:0)

您需要为子网站创建唯一 dicts,您不能重复使用相同的second_dict值,并希望这会为您的嵌套结构生成单独的字典。

使用:

resi = {k: dict(second_dict) for k in res}

代替; dict(second_dict)为每个密钥创建second_dict的新副本。