[Python] How to match an empty dictionary?

Discussão em 'Python' iniciado por Stack, Julho 8, 2025.

  1. Stack

    Stack Membro Participativo

    Python supports Structural Pattern Matching since version 3.10. I came to notice that matching an empty dict doesn't work by simply matching {} as it does for lists. According to my naive approach, non-empty dicts are also matched (Python 3.10.4):

    def match_empty(m):
    match m:
    case []:
    print("empty list")
    case {}:
    print("empty dict")
    case _:
    print("not empty")


    match_empty([]) # empty list
    match_empty([1, 2]) # not empty
    match_empty({}) # empty dict
    match_empty({'a': 1}) # empty dict


    Matching the constructors even breaks the empty list matching:

    def match_empty(m):
    match m:
    case list():
    print("empty list")
    case dict():
    print("empty dict")
    case _:
    print("not empty")


    match_empty([]) # empty list
    match_empty([1, 2]) # empty list
    match_empty({}) # empty dict
    match_empty({'a': 1}) # empty dict


    Here is a solution, that works as I expect:

    def match_empty(m):
    match m:
    case []:
    print("empty list")
    case d:
    if isinstance(d, dict) and len(d) == 0:
    print("empty dict")
    return
    print("not empty")


    match_empty([]) # empty list
    match_empty([1, 2]) # not empty
    match_empty({}) # empty dict
    match_empty({'a': 1}) # not empty


    Now my questions are:

    • Why do my first 2 approaches not work (as expected)?
    • Is there a way to use structural pattern matching to match only an empty dict (without checking the dict length explicitly)?

    Continue reading...

Compartilhe esta Página