25

Below is the file output:

apples:20
orange:100

Below is the code:

d = {}
with open('test1.txt') as f:
    for line in f:
        if ":" not in line:
                continue
        key, value = line.strip().split(":", 1)
        d[key] = value

for k, v in d.iteritems():
    if k == 'apples':
         v = v.strip()
         if v == 20:
             print "Apples are equal to 20"
         else:
             print "Apples may have greater than or less than 20"   
    if k == 'orrange':
         v = v.strip()
         if v == 20:
            print "orange are equal to 100"
         else:
            print "orange may have greater than or less than 100"

In above code i am written "if k == 'orrange':", but its actually "orange" as per output file.

In this case I have to print orrange key is not exist in output file. Please help me. How to do this

pioltking
  • 271
  • 1
  • 3
  • 8
  • 3
    Don't *iterate over a dictionary to check if a key exists*. That defeats the *whole point*. Just use `if k in d: print("the key", k, "exists and the value is", d[k])` – juanpa.arrivillaga May 17 '17 at 21:49
  • 1
    Possible duplicate of [Check if a given key already exists in a dictionary](http://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary) – Arya McCarthy May 17 '17 at 21:50
  • 3
    Also, note, your value will be `str`, which you seem to be aware because you use `v = v.strip()`, so `if v == 20` will *never be true*. Use `if int(v) == 20` – juanpa.arrivillaga May 17 '17 at 21:51
  • @juanpa.arrivillaga I thought `==` would coerce and yield expected result for `v==20`. – CᴴᴀZ Nov 21 '18 at 10:32
  • @CᴴᴀZ No, python never coerces. Python != Javascript – juanpa.arrivillaga Nov 21 '18 at 12:43
  • @juanpa.arrivillaga To test, I ran `1 == True` and it returns `True`, but `1 is True` returns `False`. Python does low-level coercion in case of `==` operator, more discussion [here](https://stackoverflow.com/questions/15008380/double-equals-vs-is-in-python). – CᴴᴀZ Nov 22 '18 at 06:44
  • @CᴴᴀZ No, it does not. `1 == True` because `isinstance(True, int)` in python, booleans *are ints* – juanpa.arrivillaga Nov 22 '18 at 16:56
  • @CᴴᴀZ in the end, `==` will do whatever `__eq__` tells it to do. – juanpa.arrivillaga Nov 22 '18 at 16:59

1 Answers1

59

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')
  • I want to print v value as well for some reasons. will above script will work in that case? – pioltking May 17 '17 at 22:02
  • 2
    Since python evaluates Boolean conditions lazily, you can simplify your 'if' statement to look like this: `if 'apples' in d and d['apples'] == 20: ...`. The interpreter will check for the 'apples' key in the dictionary, and only if it exists will the interpreter continue to fetch it. – hizki Nov 05 '18 at 10:12