如何确保键(或值)是dict中指定的数据类型?

2024-10-03 13:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我的python程序使用dicts,有大量的“if”语句只用于检查检索值的类型。在

我想避免这一点,但应该用一种更符合程序设计的方式来做。在

下面是一个例子:

# golddb should only contain str keys and int values
golddb = dict()

def gainGold(playername):
  global golddb
  golddb[playername] += 1  # error may happen if I try to += a non-int type
  golddb[playername] = "hello"  # I want python to give an error when I try to assign a str to be a value in the dict

Tags: to程序类型if方式error语句dict
2条回答

要验证dict的所有键/值是否属于特定类型,可以使用^{}函数:

if all(isinstance(k, str) for k in playerdb):
    print("all keys are strs")

为了在存储值时强制使用类型,可以使用自定义函数来调解对字典的访问,或者更好地,使用子类dict并重写{}方法,例如:

^{pr2}$

Python不是类型安全的。因此,存储在字典中的值可以是任何类型的。防止将其他类型的值添加到字典中的一种方法是定义一个函数,该函数只在类型匹配时添加数据。然后只使用此函数附加到字典中。在

def gain_gold(playername, amount):
    if isinstance(amount, int):
        playerdb[playername] = amount
    else:
       raise Exception('invalid type')

相关问题 更多 >