Dictionary of dictionaries in Python?

后端 未结 3 623
日久生厌
日久生厌 2020-12-28 17:45

From another function, I have tuples like this (\'falseName\', \'realName\', positionOfMistake), eg. (\'Milter\', \'Miller\', 4). I need to write a

3条回答
  •  一向
    一向 (楼主)
    2020-12-28 18:21

    Using collections.defaultdict is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.

    Here it's used twice: for the resulting dict, and for each of the values in the dict.

    import collections
    
    def aggregate_names(errors):
        result = collections.defaultdict(lambda: collections.defaultdict(list))
        for real_name, false_name, location in errors:
            result[real_name][false_name].append(location)
        return result
    

    Combining this with your code:

    dictionary = aggregate_names(previousFunction(string))
    

    Or to test:

    EXAMPLES = [
        ('Fred', 'Frad', 123),
        ('Jim', 'Jam', 100),
        ('Fred', 'Frod', 200),
        ('Fred', 'Frad', 300)]
    print aggregate_names(EXAMPLES)
    

提交回复
热议问题