【问题标题】:Searching a prefix in list of dictionaries in python在python中的字典列表中搜索前缀
【发布时间】:2021-11-17 08:14:17
【问题描述】:

我目前有一个字典列表

list_of_dicts = [{"name": 'stfdahbancssc',"status":'running'},
                 {"name": 'stfdahbancssc',"status":'running'}]

我想检查如何匹配前缀 'stf' 并打印 stf 存在,否则 stf 不存在。

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    迭代字典,获取“名称”值,检查前缀,打印消息:

    list_of_dicts = [{"name": 'stfdahbancssc',"status":'running'},
                    {"name": 'stfdahbancssc',"status":'running'},
                    {"name": 'none'}]
    
    for idx,d in enumerate(list_of_dicts): 
        if d.get("name","").startswith("stf"):
            v = d["name"]
            s = d["status"]
            print(f"The {idx} dictionary has {v} as {s}")
            print("a")
        else:
            print(f"The {idx}. dictionary has no name starting with 'stf'.")    
    

    输出:

    【讨论】:

    • 如果我还想检查状态是否正在运行,我该如何在此处进行更改。假设另一个字典有错误状态
    • @kshi 我建议以docs.python.org/3/tutorial 为起点,学习如何使用pythons list / dict / etc,而不是移动你的问题的目标帖子......
    猜你喜欢
    • 2020-01-01
    • 2022-11-12
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    相关资源
    最近更新 更多