代码之家  ›  专栏  ›  技术社区  ›  Ali

是否有更简洁的方法来获取相应的字典值

  •  0
  • Ali  · 技术社区  · 6 年前

    用户输入宠物名称,如果在字典中找到,代码将返回宠物的价格,否则要求用户尝试其他名称。想知道这是否可以用更少的代码行以更干净的方式完成?

    pets = {'bird': 3.5, 'cat': 5.0, 'dog': 7.25, 'gerbil': 1.5}
    
    while True:
    
        req_pet = input("Enter pet name: ")
    
        if req_pet in pets:
            for (pet, price) in pets.items():
                if pet == req_pet:
                    print(price)
                    exit(0)
        else:
            print("Pet not found, let's try a different one?")
    
    0 回复  |  直到 6 年前
        1
  •  5
  •   match    6 年前

    你可以通过做以下事情来减少一点:

    try:
      print(pets[input("Enter pet name: ")])
      exit(0)
    except KeyError:
      print("Pet not found, let's try a different one?")
    

    这会在字典中显式查找输入“key”,并打印值并退出。如果密钥不存在,它会捕获错误并打印消息。

    如果你不需要 exit 通过这种方式,它可以变得更短 get 返回默认消息:

    print(pets.get(input("Enter pet name: "), "Pet not found, let's try a different one?")
    
        2
  •  3
  •   Thierry Lathuille    6 年前

    对字典项进行迭代以查找关键字违背了字典的原则,效率非常低。只需直接访问它:

    pets = {'bird': 3.5, 'cat': 5.0, 'dog': 7.25, 'gerbil': 1.5}
    
    while True:
    
        req_pet = input("Enter pet name: ")
    
        if req_pet in pets:
            print(pets[req_pet])
            exit(0)
        else:
            print("Pet not found, let's try a different one?")