Python: How to update value of key value pair in nested dictionary?

后端 未结 9 986
广开言路
广开言路 2021-01-21 20:25

i am trying to make an inversed document index, therefore i need to know from all unique words in a collection in which doc they occur and how often.

i have used this an

9条回答
  •  臣服心动
    2021-01-21 21:07

    One could use Python's collections.defaultdict instead of creating an AutoVivification class and then instantiating dictionary as an object of that type.

    import collections
    dictionary = collections.defaultdict(lambda: collections.defaultdict(int))
    

    This will create a dictionary of dictionaries with a default value of 0. When you wish to increment an entry, use:

    dictionary[keyword][filename] += 1
    

提交回复
热议问题