简体   繁体   English

Python 3 中的模式匹配字典

[英]Pattern matching dictionaries in Python 3

I'm trying to pattern match elements from a python dictionary, something like the following:我正在尝试从 python 字典中模式匹配元素,如下所示:

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?有没有办法在 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.我有一个函数,它返回一个相当大的字典,而不是花费 20 行来解构它,我真的很想能够只对数据进行模式匹配。

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.史蒂夫 5 岁。

This is not really a language feature but you could use the unpack operator as a workaround:这并不是真正的语言功能,但您可以使用 unpack 运算符作为解决方法:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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