【问题标题】:How to check whether a dictionary contains integer or string in python?如何在python中检查字典是否包含整数或字符串?
【发布时间】:2021-02-24 16:50:18
【问题描述】:

我是 python 新手,字符串有问题我有一个像这样的字典{'roads': '20' , 'rails': 'three'}。我想知道字典的值是否是int or str。我该怎么做?

input:
dict = {'roads': '20' , 'rails': 'three'}
Expected output:
dict = {'roads': 'int' , 'rails': 'object'}

【问题讨论】:

  • 不要将变量命名为dict,否则当您尝试调用内置的dict 函数时,您最终会遇到非常混乱的错误!
  • @Samwise 哦,谢谢,我会跟进的

标签: python string integer


【解决方案1】:

您可以使用string.isdigit() 来检查某事是数字

dictionary = {'roads': '20' , 'rails': 'three'}

output = {k: 'int' if v.isdigit() else 'object' for k,v in dictionary.items()}
{'roads': 'int', 'rails': 'object'}

【讨论】:

  • 但是如果值是浮点数,比如 20.003 而不是 20
  • 为了安全起见,您可以使用v.replace('.', '').isdigit(),但不是int,而是float
猜你喜欢
  • 2015-11-12
  • 2017-02-27
  • 2011-03-23
  • 1970-01-01
  • 2013-03-04
  • 1970-01-01
  • 2020-06-27
  • 2021-09-13
  • 1970-01-01
相关资源
最近更新 更多