如何在python中检查字典是否包含整数或字符串?

时间:2021-02-24 16:50:18

标签: python string integer

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

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

1 个答案:

答案 0 :(得分:2)

您可以使用 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'}
相关问题