我需要通过从字典中提取信息来创建列表

时间:2016-06-17 07:24:16

标签: python dictionary

我编写了一个代码,用于从AWS中提取所有正在运行的公共IP。这将以dict的形式返回数据。代码运行如下:

for region in regions:
    instance_information = {}
    ip_dict = {}
    client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
    addresses_dict = client.describe_addresses().get('Addresses')

    for address in addresses_dict:

        if address.get('InstanceId'):
            instance_information[address['InstanceId']] = [address.get('PublicIp')]
         #   print  instance_information

    dex_dict = client.describe_tags().get('Tags')
    for dex in dex_dict:
        if instance_information.get(dex['ResourceId']):
            instance_information[dex['ResourceId']].append(dex.get('Value'))
    for instance in instance_information:

        if len(instance_information[instance]) == 2:
            ip_dict[instance_information[instance][0]] = instance_information[instance][1]
        else:
            ip_dict[instance_information[instance][0]] = ''
    print (json.dumps(instance_information,indent=4))
    print type(instance_information)

这将结果显示为:

{
    "i-cqa1ea32": [
        "22.40.13.171", 
        "Prod LB", 
        "pdx-ms-prod--lb01"
    ], 
    "i-b86adf671": [
        "12.6.1.3", 
        "pdx-trial-LBi", 
        "HAProxy Server", 
        "us-west-2", 
        "pdx-cloud-trial", 
        "subnet-d8e1af", 
        "us-west-2b"
    ], 
    "i-47dabsa1": [
        "12.5.124.146", 
        "SDL Exclusive LB", 
        "pdx01-ms-prod-sdl-lb02"
    ], 
    .
    . 
    .

现在这是一个类型dict,我需要提取IP,标签名称和区域,所以基本上是从上面的数据映射为

IP , Tag Name, Region 

前:

['12.1.1.1','pdx-dev-server','us,west-1']
['12.1.1.3','pdx-dev-server1','ap-southeast-1']
..
..

但有些dict对象没有区域等。如何从上述数据中创建list,我需要实际将IP地址传递(返回)到另一个代码。 请帮助

1 个答案:

答案 0 :(得分:0)

如果i [0]确实是IP,i [1]是Tag,i [3]是Region,你可以使用这个函数:

def dict_to_list(dict_in):
    ip_list = [i[0] for i in dict_in.values()]
    tag_list = [i[1] for i in dict_in.values()]
    region_list = []
    for i in dict_in.values():
        try:
            region_list.append(i[3])
        except:
            region_list.append("")
    combined_result = list(zip(ip_list, tag_list, region_list))
    return combined_result