【问题标题】:Is there a better way to access this dictionary in python?有没有更好的方法在 python 中访问这个字典?
【发布时间】:2019-12-21 00:52:49
【问题描述】:

我对 python 有点陌生,并且已经完成了编程,我知道这是基本的,但我的大脑现在已经融化了。

我需要对代表类别的 id 进行分类,例如: id: 12312 => 食物 id: 123132 => 食物

但我在字典中输入每个id 的类别,有更好的方法: 喜欢:{[food:{12132,1444,54556,444},gas:{233,566,555}]} 但随后它需要按该值查找并提供相应的猫...

这是我的代码

def clasificadorTipoGasto(id):
    dict = {
        131794442: "Gastos Menores", 101602465: "Supermercados",
        130403899: "Supermercados", 101793198: "Supermercados",
        101796822: "Supermercados", 101787589: "Supermercados",
        130246491: "Restaurantes", 124003091: "Restaurantes",
        101658347: "Restaurantes", 130123314: "Restaurantes",
        130751366: "Restaurantes", 101568224: "Restaurantes",
        130640726: "Restaurantes", 101808152: "Restaurantes",
        130389586: "Restaurantes", 101582936: "Air Fare",
        101068744: "Combustible", 101726997: "Combustible",
        130551618: "Combustible", 101033738: "Combustible",
        130274487: "Misc", 112107388: "Misc",
        130900663: "Misc", 101036354: "Misc"
    }

    if id in dict.keys():

        return dict[id]
    else:
        return "general"

【问题讨论】:

    标签: python python-3.x list dictionary


    【解决方案1】:

    dict.get 将尝试返回映射到给定键的值,但如果查找失败则返回默认值,而不是引发 KeyError

    def clasificadorTipGasto(id):
        d = {...}
    
        return d.get(id, "general")
    

    如果您尝试从另一个将类别映射到不同 ID 的字典生成该字典 d,请尝试

    ids = {"food": {12132,1444,54556,444}, "gas": {233,566,555}}
    d = {cat_id: category for category in ids for cat_id in ids[category]}
    

    【讨论】:

    • 这应该是个愚蠢的问题,但是,现在我需要将 01239129 数字作为字符串进行比较,我尝试将 '20320' 数字封装起来,现在它会将所有内容都抛出为 "General" ,而不是分类.. @chepner
    【解决方案2】:

    你可以简单地返回:

    return d.get(id, "general")
    

    这里的第二个参数是没有找到key时返回的默认值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      相关资源
      最近更新 更多