检查键出现在python词典中

时间:2017-05-18 09:25:36

标签: python python-2.7

以下是"数据"字典

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

我正在尝试在下面的代码中的数据字典中存在或不存在关键节点2但它不起作用。请帮忙

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

2 个答案:

答案 0 :(得分:1)

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

这是确定某个键是否在词典中的完美选择,遗憾的是'node2'不在您的词典中,' node2'是(注意空格):

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

答案 1 :(得分:0)

检查键出现在字典中:

data = {' node2':{'状态':'在线',' TU':' 900',' Link':' up',' Port':' a0a-180',' MTU':' 9000'},' node1':{'状态':'在线',' TU':' 900',' Link':' up',' Port':' a0a-180',' MTU':' 9000'}}

在python 2.7版本中:

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

在python 3.x版本中:

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