Python: Checking if a 'Dictionary' is empty doesn't seem to work

前端 未结 8 586
旧巷少年郎
旧巷少年郎 2020-12-02 04:27

I am trying to check if a dictionary is empty but it doesn\'t behave properly. It just skips it and displays ONLINE without anything except of display the m

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 04:55

    You can also use get(). Initially I believed it to only check if key existed.

    >>> d = { 'a':1, 'b':2, 'c':{}}
    >>> bool(d.get('c'))
    False
    >>> d['c']['e']=1
    >>> bool(d.get('c'))
    True
    

    What I like with get is that it does not trigger an exception, so it makes it easy to traverse large structures.

提交回复
热议问题