使用字典作为查找表

Fly*_*der 2 python dictionary operating-system jinja2 python-3.x

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

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

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

countries = {"PL" : "countries/flags/poland.png"}
Run Code Online (Sandbox Code Playgroud)

其中应用程序文件夹的系统路径随后在 Python 中通过os.path.

我的问题:如何使用我获得的国家/地区字符串自动转换为国家/地区的路径格式?就像是:

for data in countries:
    if data in countries.keys:
        return countries.value
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Mar*_*lli 6

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

def get_path(data):
    return countries.get(data)
Run Code Online (Sandbox Code Playgroud)

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

如果您想要一个默认值,而不是None当键不存在时,您可以将其指定为第二个参数,如下所示:

def get_path(data):
    return countries.get(data, "default/path/x/y/z")
Run Code Online (Sandbox Code Playgroud)