Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare dictionary values and key in python

Tags:

python

I have a dictionary item. It has strings as keys and the values are lists e.g.:

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

I want to check if any value is 0 in length, but link or image may be empty, so I did the following:

        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

So an item should be dropped only if the value is 0 and it is not an image or a key. My problem is now that this condition does not work. The item is still dropped when the image or link is empty.

Any idea whats wrong? (I am new to python^^)

like image 791
UpCat Avatar asked Mar 29 '26 02:03

UpCat


2 Answers

You confused the logical or with and. For example, if the key is "image", you check the following:

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

Instead, you want

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

or, easier to read:

if key not in ('image', 'link'):
like image 148
phihag Avatar answered Apr 01 '26 11:04

phihag


You should :

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

because

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

is always true

like image 45
develerx Avatar answered Apr 01 '26 11:04

develerx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!