python 字符串if 判断问题

`{'_type': 'video', 'extraction_tags': '', 'user_id': '2077093354', 'highlight': None, 'user_info': '{"id":2077093354,"avatar_url":"https:\\/\\/krplus-pic.b0.upaiyun.com\\/avatar\\/201806\\/05084648\\/f1ggwy0wqraluwdz","name":"\\u8d22\\u7ea6\\u4f60","nickname":"\\u8d22\\u7ea6\\u4f60"}', 'project_id': '1', 'vtype': 'normal', 'published_at': '2018-11-13T14:31:09+08:00', 'tag_id': '0', '_score': None, 'column_id': '213', 'title': '商业传奇褚时健:有朋友劝我不要干,但人生总要做些贡献', 'cover': 'https://pic.36krcnd.com/201811/12082329/jhu9pf7ggeosdbft!heading', 'template_info': {'template_extra': {'vtype': 'normal'}, 'template_type': 'small_image', 'template_title': '商业传奇褚时健:有朋友劝我不要干,但人生总要做些贡献', 'template_title_isSame': True, 'template_cover': ['https://pic.36krcnd.com/201811/12082329/jhu9pf7ggeosdbft!heading']}, 'web_cover': 'https://pic.36krcnd.com/201811/12082256/sekti37ljzprt2hj', 'column_name': '商业·氪视频', 'id': '24250', 'summary': '褚时健在谈到人生的触底反弹时说,人生哪个没有错,错可以改正,人总要为社会为国家做些贡献。“有朋友劝我算了不要干`了,我说不要再错总是能做到的。”'}

<class 'dict'>
这个字典里面有video 我这样直接判断不行吗?

if 'video' not in (content):
         title_list.append(content['template_info']['template_title'])
         time_list.append(content['published_at'])
         link_list.append("https://36kr.com/p/{}.html".format(content['id']))
         

我这里content 不用str 总是不能判断,加了str 就可以判断了
这是为啥呢?

阅读 2.9k
1 个回答

因为str中的in 跟字典中的in 的用法不同。

  • 你加了str(content)就是把字典转化为字符串,用in判断即为content字符串中是否含有'video',显然是有的。
  • 如果你在字典中用in,仅仅判断key是否在dict中,而'video'为字典的值,所以结果为空。

具体的用法,见下面例子

In [1]: dict_demo = {"h":"hello","w":"world"}

In [2]: if "hello" in dict_demo:
   ...:     print("hello yes")
   ...:     

In [3]: if "h" in dict_demo:
   ...:     print("h yes")
   ...:     
h yes

In [4]: if "hello" in str(dict_demo):
   ...:     print("hello in string")
   ...:     
hello in string

如果你要判断值是否存在,可以使用dict.values()方法,如下

In [5]: if "hello" in dict_demo.values():
   ...:     print("hello in values")
   ...:     
hello in values
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题