如何从函数返回dict?

时间:2017-04-12 07:48:20

标签: python python-2.7 dictionary

我有一小段代码:

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

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

3 个答案:

答案 0 :(得分:2)

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

ca-app-pub-XXXXXXXXXX/XXXXXXXXXX

我希望它可以工作:)

答案 1 :(得分: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']

答案 2 :(得分: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'
相关问题