2017-04-12 19 views
0

は、私は、コードの小片を持っている:関数からdictを返すにはどうすればよいですか?

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

あなたは発電機を使用することができますが、私はあなたのpythonに新しいですし、これは単純になります推測している:

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

関連する問題