【问题标题】:How to tell if a variable is a specific type of dictionary? i.e. dict(int, str)如何判断变量是否是特定类型的字典?即 dict(int, str)
【发布时间】:2018-11-17 18:41:10
【问题描述】:

我有一本字典 -

d = dict(
    0='a',
    1='b',
    2='c'
)

如何判断 d 是否是 dict 类型的 (int, str)

在 C# 中是这样的:

d.GetType() == typeof(Dictionary<int, string>)

【问题讨论】:

  • 字典没有特定的类型。
  • 您可以混合和匹配不同类型的键和值。 d = {0:'a', 'foo': 1}
  • 这不是定义python dict的有效方法
  • 如前所述,dicts 是异质的,你必须检查每个项目以确保,例如[(type(k),type(v)) for k,v in d.items()]
  • 这不是你做鸭子打字的方式。 Python 不关心它是否是特定类型,它关心它是否行为 像某个特定类型。

标签: python dictionary types isinstance


【解决方案1】:

Python 字典没有类型。您实际上必须检查每个键和值对。例如

all(isinstance(x, basestring) and isinstance(y, int) for x, y in d.items())

【讨论】:

    【解决方案2】:

    在单个 Python 字典中,值可以是任意类型。密钥还有一个额外要求,即它们必须是可散列的,但它们也可能涵盖多种类型。

    要检查字典中的键或值是否属于特定类型,您可以对其进行迭代。例如:

    values_all_str = all(isinstance(x, str) for x in d.values())
    keys_all_int = all(isinstance(x, int) for x in d)
    

    【讨论】:

      【解决方案3】:

      如果您使用的是 Python 3.7,您可以执行以下操作:

      from typing import Dict
      
      d: Dict[int, str] = { 0: 'a', 1: 'b', 2: 'c' }
      
      print(__annotations__['d'])
      

      然后返回:typing.Dict[int, str]

      有一个函数typings.get_type_hints 将来可能有用,但目前只知道对象类型:

      函数、方法、模块或类

      PEP-0526 也表示要对此采取措施

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-02
        • 2016-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-20
        • 2010-12-16
        相关资源
        最近更新 更多