简体   繁体   中英

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.

person = {"name": "Steve", "age": 5, "gender": "male"}

my_str = "{name} is {age} years old.".format(**person)

print(my_str)

Steve is 5 years old.

This is not really a language feature but you could use the unpack operator as a workaround:

def is_driving_age(age, **_):
    return age > 17
def print_result(drives, name, age, **_):
    print(f"{name} is {age} years old. He {'can' if drives else 'is not allowed to'} drive.")

person = {"name": "Steve", "age": 5, "gender": "male"}

drives = is_driving_age(**person)
print_result(drives, **person)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM