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

后端 未结 9 1054
广开言路
广开言路 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:27

    I think you are trying to add 1 to a dictionary entry that doesn't yet exist. Your getitem method is for some reason returning a new instance of the AutoVivification class when a lookup fails. You're therefore trying to add 1 to a new instance of the class.

    I think the answer is to update the getitem method so that it sets the counter to 0 if it doesn't yet exist.

    class AutoVivification(dict):
        """Implementation of perl's autovivification feature."""
        def __getitem__(self, item):
            try:
                return dict.__getitem__(self, item)
            except KeyError:
                self[item] = 0
                return 0
    

    Hope this helps.

提交回复
热议问题