-2

Below is the "data" dict

{' node2': {'Status': ' online', 'TU': ' 900', 'Link': ' up', 'Port': ' a0a-180', 'MTU': ' 9000'}, ' node1': {'Status': ' online', 'TU': ' 900', 'Link': ' up', 'Port': ' a0a-180', 'MTU': ' 9000'}}

I am trying key node2 is present or not in data dict in below code but it is not working. Please help

if 'node2' in data:
    print "node2 Present"
else:
    print "node2Not present"
pioltking
  • 279
  • 1
  • 3
  • 9

2 Answers2

1
if 'node2' in data:
    print "node2 Present"
else:
    print "node2Not present"

This is a perfectly appropriate way of determining if a key is inside a dictionary, unfortunately 'node2' is not in your dictionary, ' node2' is (note the space):

if ' node2' in data:
    print "node2 Present"
else:
    print "node2Not present"
Nick is tired
  • 6,860
  • 20
  • 39
  • 51
0

Check key is present in dictionary :

data = {'node2': {'Status': ' online', 'TU': ' 900', 'Link': ' up', 'Port': ' a0a-180', 'MTU': ' 9000'}, ' node1': {'Status': ' online', 'TU': ' 900', 'Link': ' up', 'Port': ' a0a-180', 'MTU': ' 9000'}}

In python 2.7 version:

has_key()-Test for the presence of key in the dictionary.

if data.has_key('node2'):
    print("found key") 
  else:
    print("invalid key")

In python 3.x version:

key in d - Return True if d has a key, else False.

  if 'node2' in data:
    print("found key") 
  else:
    print("invalid key")
bharatk
  • 4,202
  • 5
  • 16
  • 30
  • 1
    You should point out ``has_key`` is removed in Python 3.x (and it's not very pythonic anyway). Source: [Removed. dict.has_key() – use the in operator instead.](https://docs.python.org/3.1/whatsnew/3.0.html#builtins) [I realize the question is flagged "python-2.7", but for the sake of completeness it should be pointed out] - but the "problem" in OP's question is the space in the key. – Mike Scotty May 18 '17 at 09:47