Python字典键错误..列表中字典中的字典乱七八糟

时间:2012-08-09 20:07:10

标签: python debugging

这有点令人费解,所以如果我错过了一个简单的构造,请告诉我:)

我正在分析一些匹配实验的结果。在最后的游戏中,我希望能够查询诸如experiments[0]["cat"]["cat"]之类的内容,这会产生“cat”与“cat”匹配的次数。相反,我可以experiments[0]["cat"]["dog"],当第一个查询是一只猫并且匹配尝试是一只狗时。

以下是填充此结构的代码:

    # initializing the first layer, a list of dictionaries.
    experiments = []
    for assignment in assignments:
        match_sums = {}
        experiments.append(match_sums)


for i in xrange(len(classes)):
        for experiment in xrange(len(experiments)):
            # experiments[experiment][classes[i]] should hold a dictionary,
            # where the keys are the things that were matched against classes[i], 
            # and the value is the number of times this occurred.
            experiments[experiment][classes[i]] = collections.defaultdict(dict)

            # matches[experiment][i] is an integer for what the i'th match was in an experiment.
            # classes[j] for some integer j is the string name of the i'th match. could be "dog" or "cat".
            experiments[experiment][classes[i]][classes[matches[experiment][i]]] += 1
            total_class_sums[classes[i]] = total_class_sums.get(classes[i], 0) + 1

    print experiments[0]["cat"]["cat"]
    exit()

很明显,这有点令人费解。我在最后一场比赛中获得的值为“1”,而不是experiments[0]["cat"]的完整字典。我接近这个错了吗?这里的错误是什么?对不起,感谢疯狂,感谢任何可能的帮助!

2 个答案:

答案 0 :(得分:2)

两点:

  • 字典键可以是元组;和
  • 如果您正在计算内容,请使用collections.Counter。 (您可以使用defaultdict(int),但Counter更有用。)

所以,而不是

experiments[experiment][classes[i]][classes[matches[experiment][i]]] += 1

experiments = Counter()
...
experiments[experiment, classes[i], classes[matches[experiment][i]]] += 1

答案 1 :(得分:0)

我只是想猜测你的需求,所以我试图改变你的尺寸顺序。

for className, classIdx in enumerate(classes):
    experiment = collections.defaultdict(list)
    experiments[className] = experiment
    for assignment,assignmentIdx in enumerate(assignments):
        counterpart = classes[matches[assignmentIdx][classIdx]]
        experiment[counterpart].append((assignment,assignmentIdx))

print(len(experiments["cat"]["cat"]), len(experiments["cat"]))