You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python字典的值映射到自定义函数参数并传入?

问题:如何将字典值映射到函数参数?

我定义了一个Python字典mpm_holidays:

mpm_holidays = {
    "New Year's Day (Observed)": (None, True),
    "Martin Luther King Jr. Day": ("art/MLKDay.png", True),
    "2022-02-14": ("art/ValentinesDay.png", False),
    "Good Friday": ("art/GoodFriday.png", True),
    "2022-04-16": ("art/GoodFriday.png", True),
    "Memorial Day": ("art/MemorialDay.png", True),
    "2022-05-28": (None, True),
    "2022-06-19": ("art/Juneteenth.png", False),
    "Independence Day": ("art/IndependenceDay.png", True),
    "Independence Day (Observed)": (None, True),
    "Labor Day": ("art/LaborDay.png", True),
    "2022-09-03": (None, True),
    "2022-09-05": (None, True),
    "Veterans Day": ("art/VeteransDay.png", True),
    "Veterans Day (Observed)": (None, True),
    "2022-10-31": ("art/Halloween.png", False),
    "Thanksgiving": ("art/Thanksgiving.png", True),
    "Day After Thanksgiving": (None, True),
    "Christmas Eve": ("art/ChristmasEve.png", True),
    "Christmas Eve (Observed)": (None, True),
    "Christmas Day": ("art/ChristmasDay.png", True),
    "New Year's Eve": ("art/NewYearsEve.png", True)
}

同时编写了函数overlays:

def overlays(art_to_use_, closure_):
    """ Imprint closure and/or holiday artwork. """
    if art_to_use_:
        calendarSheet.paste(
            Image.open(art_to_use_).convert("RGBA"),
            (0, 0),
            mask=Image.open(art_to_use_).convert("RGBA")
        )
    if closure_:
        calendarSheet.paste(
            Image.open(STATUS_CLOSED).convert("RGBA"),
            (0, 0),
            mask=Image.open(STATUS_CLOSED).convert("RGBA")
        )
    calendarSheet.save(calendarSheetFilename, format="png")

现在不清楚如何将字典的值映射到函数所需的参数,请问该如何实现?


解决方案

你的字典每个值都是二元元组,正好和overlays函数的两个参数art_to_use_(元组第一个元素)、closure_(元组第二个元素)一一对应,直接用Python的元组解包语法就能实现映射,具体分两种场景:

1. 针对单个节日/日期处理

如果你想处理字典里的某一个特定条目,比如"Martin Luther King Jr. Day",可以这样做:

# 获取对应的值元组
holiday_data = mpm_holidays["Martin Luther King Jr. Day"]
# 解包元组传入函数,等同于 overlays("art/MLKDay.png", True)
overlays(*holiday_data)

2. 遍历整个字典批量处理

如果需要处理字典里的所有条目,直接遍历字典的值即可:

for holiday_data in mpm_holidays.values():
    overlays(*holiday_data)

额外优化建议

注意你的函数里两次打开同一张图片(比如Image.open(art_to_use_)),可以优化成只打开一次,避免重复IO操作:

def overlays(art_to_use_, closure_):
    """ Imprint closure and/or holiday artwork. """
    if art_to_use_:
        img = Image.open(art_to_use_).convert("RGBA")
        calendarSheet.paste(img, (0, 0), mask=img)
    if closure_:
        closed_img = Image.open(STATUS_CLOSED).convert("RGBA")
        calendarSheet.paste(closed_img, (0, 0), mask=closed_img)
    calendarSheet.save(calendarSheetFilename, format="png")

内容的提问来源于stack exchange,提问作者stunafish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 00:55:16