2017-04-12 83 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