如何从函数返回dict?

2024-03-28 15:29:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一小段代码:

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并从这里返回。还曾经返回过如何使用字典值


Tags: 代码inidjsonhomeforreturndef
3条回答
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'

您可以使用生成器,但我猜您是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']

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

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

我希望它能起作用:)

相关问题 更多 >