2017-04-12 86 views
0

我有一个小小的一段代码:如何从函数返回字典?

def extract_nodes(): 
    for i in json.load(open('/home/ubuntu/slcakbot_openNMS/CLEAR/out.txt'))["node"]: 
     try: 
      socket.inet_aton(i["label"]) 
      print(i["label"]) 
      print(i["id"]) 
      #return { 'ip': i["label"], 'id': i["id"]} # i need to return these values 

     except Exception as e: 
      pass 

我需要创建一个字典,并返回给调用函数,我不知道如何创建一个字典,从这里返回。也一次返回如何使用字典的值

+2

永远不要捕获异常并通过。它会隐藏任何可能将您直接指向问题解决方案的错误。如果你不想在异常情况下做任何事情,你应该登录甚至只是打印它。 – chatton

+0

为什么不使用注释掉的return语句?另外,如果循环迭代多次,会发生什么? – augurar

+0

@augurar所以如果我把注释掉的行......循环中断只返回第一个值..我需要返回所有值 – Kittystone

回答

2

关键字“id”和“label”可能有多个值,因此您应该考虑使用列表。 这里是我的代码

def extract_nodes(): 
    labels = [] 
    ids = [] 
    results = {} 
    for i in json.load(open('/home/ubuntu/slcakbot_openNMS/CLEAR/out.txt'))["node"]: 
     try: 
      socket.inet_aton(i["label"]) 
      print(i["label"]) 
      labels.append(i["label"]) 
      print(i["id"]) 
      ids.append(i["id"]) 
      #return { 'ip': i["label"], 'id': i["id"]} # i need to return these values 

     except Exception as e: 
      pass 
    results['ip']=labels 
    results['id']=ids 
    return results 

我希望它可以工作:)

0
def extract_nodes(): 
    to_return_dict = dict() 
    for i in json.load(open('/home/ubuntu/slcakbot_openNMS/CLEAR/out.txt'))["node"]: 
     try: 
      socket.inet_aton(i["label"]) 
      to_return_dict[i['id']] = i['label'] 
      print(i["label"]) 
      print(i["id"]) 
      #return { 'ip': i["label"], 'id': i["id"]} # i need to return these values 

     except Exception as e: 
      pass 
    return to_return_dict 

这应该做它....让我知道它是否工作!

编辑:

至于如何使用它:

id_label_dict = extract_nodes() 
print(id_label_dict['ip']) # should print the label associated with 'ip' 
1

你可以使用一个发电机,但我猜你是新的蟒蛇,这将是简单的:

def extract_nodes(): 
    return_data = dict() 
    for node_datum in json.load(open('/home/ubuntu/slcakbot_openNMS/CLEAR/out.txt'))["node"]: 
     try: 
      socket.inet_aton(node_datum["label"]) 
      return_data[node_datum["id"]] = { 'ip': node_datum["label"], 'id': node_datum["id"]} 
      print(node_datum["label"]) 
      print(node_datum["id"]) 
      #return { 'ip': node_datum["label"], 'id': node_datum["id"]} # i need to return these values 

     except Exception as err: 
      print err 
      pass 

    return return_data 

至于使用它,

node_data = extract_nodes() 
for key, node_details in node_data.items(): 
    print node_details['ip'], node_details['id'] 
+0

这不是返回任何东西 – Kittystone

+0

它适用于我的示例数据 - 它打印什么?我猜你的数据不像预期的那样。 – user3610360