比较Python中的字典值和键

2 投票
2 回答
1453 浏览
提问于 2025-04-17 01:23

我有一个字典 item。这个字典的键是字符串,而值是列表,比如:

item['title'] = [u'python']
item['image'] = [u'/link/to/image']
item['link'] = [u'link to article']

我想检查一下有没有值的长度是0的情况,但链接或图片可能是空的,所以我做了以下操作:

        for key, value in item.iteritems():
            if len(value) == 0:
                if key != 'image' or key != 'link':
                    raise DropItem("Item is empty: %s" %item)                   
        return item

所以,只有当值是0并且它不是图片或键的时候,才应该删除这个项目。现在我遇到的问题是,这个条件没有起作用。当图片或链接为空时,项目还是被删除了。

有没有人知道哪里出错了?(我刚学python^^)

2 个回答

4

你应该:

if key != 'image' and key != 'link':

因为

 if key != 'image' or key != 'link':

总是成立

5

你把逻辑运算中的搞混成了。比如说,如果关键字是"image",你应该检查以下内容:

if "image" != 'image' or "image" != 'link':
#if      False        or        True:
#if True:

其实,你想要的是:

if key != 'image' and key != 'link':

或者,写得更清楚一些:

if key not in ('image', 'link'):

撰写回答