Search code examples
pythonpython-3.xdictionarypattern-matching

Pattern matching dictionaries in Python 3


I'm trying to pattern match elements from a python dictionary, something like the following:

person = {"name": "Steve", "age": 5, "gender": "male"}
{"name": name, "age": age} = person # This line right here
drives = is_driving_age(age)

print f"{name} is {age} years old. He {'can' if drives else 'can\'t'} drive."

# Output: Steve is 5 years old. He can't drive.

Is there a way to do something like this in Python 3? I have a function that returns a fairly large dictionary, and rather than spending 20 lines deconstructing it I'd really love to be able to just pattern match out the data.

EDIT: The first few answers here assumed I'm just trying to print out the data, probably lack of clarity on my part. Note that I'm not just trying to print out the data, I'm trying to use it for further calculations.


Solution

  • As of Python 3.10, structural pattern matching is now part of the language!

    https://peps.python.org/pep-0636/#going-to-the-cloud-mappings

    person = {"name": "Steve", "age": 5, "gender": "male"}
    match person:
        case {"name": name, "age": age}:  # This line right here
            drives = is_driving_age(age)
            print(f"{name} is {age} years old. He {'can' if drives else 'can\'t'} drive.")
    

    Extra keys in the mapping will be obviated while matching unless you capture them with

    match person:
        case {"name": name, "age": age, **extra}:
            # ...
    

    See also