使用字典作为查找表

问题描述 投票:1回答:1

我有一个jinja模板,我想传递一个值(国家的标识符)。数据格式是两个字母的国家代码(例如波兰的"PL")。

通过模板,我需要传递相应的标志作为输出,但标志保存在app文件夹结构中,所以我需要获取图像的路径。

我的问题:我无法找到在jinja中使用os.path的方法,所以现在我试图通过创建一个匹配国家字符串和相对路径的字典来解决它:

countries = {"PL" : "countries/flags/poland.png"}

之后在Python中通过os.path添加app文件夹的系统路径。

我的问题:我怎样才能使用我所获得的国家字符串来自动转换为国家的路径格式?就像是:

for data in countries:
    if data in countries.keys:
        return countries.value

提前致谢!

python python-3.x dictionary operating-system jinja2
1个回答
4
投票

假设data是国家代码(例如"PL"):

def get_path(data):
    return countries.get(data)

get()方法检查字典是否有密钥,如果是,则返回相应的值,否则返回None

如果在键不存在时需要None以外的默认值,则可以将其指定为第二个参数,如下所示:

def get_path(data):
    return countries.get(data, "default/path/x/y/z")
© www.soinside.com 2019 - 2024. All rights reserved.