将字典列表转换为字典

时间:2019-10-06 02:40:53

标签: python python-3.x dictionary

我有要转换成一本词典的词典列表

vpcs = [{'VPCRegion': 'us-east-1', 'VPCId': '12ededd4'},
       {'VPCRegion': 'us-east-1', 'VPCId': '9847'},
       {'VPCRegion': 'us-west-2', 'VPCId': '99485003'}]

我想将其转换为

       {'us-east-1': '12ededd4', 'us-east-1': '9847', 'us-west-2': '99485003'}

我使用了此功能

def convert_dict(tags):
    return {tag['VPCRegion']:tag['VPCId'] for tag in tags}

但是获得此输出不会转换列表中的第一个字典

    {'us-east-1': '9847', 'us-west-2': '99485003'}

2 个答案:

答案 0 :(得分:1)

也许词典列表可能适合您的需要-请参见下面的代码: [{'us-east-1':'12ededd4'},{'us-east-1':'9847'},{'us-west-2':'99485003'}]

要详细说明其他关于字典键的注释必须唯一,您可以看到,如果'vpcs'具有2个重复的'VPCRegion',则在注释行中将list_dict压缩起来会导致错误: 1”并成功创建新的dict(如果您删除“ VPCRegion”之一:“ us-east-1”)。

vpcs = [{'VPCRegion': 'us-east-1', 'VPCId': '12ededd4'},
     {'VPCRegion': 'us-east-1', 'VPCId': '9847'},
     {'VPCRegion': 'us-west-2', 'VPCId': '99485003'}]

def changekey(listofdict):
 new_dict = {}
 new_list = []

 for member in listofdict:
     new_key = member['VPCRegion']
     new_val = member['VPCId']
     new_dict.update({new_key:new_val})
     new_list.append({new_key:new_val})
 return new_dict, new_list                                                                                              


dict1,list_dict=changekey(vpcs)
print(dict1)
print(list_dict)
#dict4=dict(zip(*[iter(list_dict)]*2))
#print(dict4)

答案 1 :(得分:0)

由于您的输出必须将同一个名称下的多个值分组,因此您的输出将是列表的字典,而不是字符串的字典。

一种快速执行此操作的方法:

import collections

def group_by_region(vpcs):
  result = collections.defaultdict(list)
  for vpc in vpcs:
   result[vpc['VPCRegion']].append(vpc['VPCId'])
  return result

group_by_region(vpcs)的结果将是{'us-east-1': ['12ededd4', '9847'], 'us-west-2': ['99485003']})

作为一种娱乐方式,这是一种隐秘但有效的表达方式,可以通过一种表达方式实现:

import itertools

{key: [rec['VPCId'] for rec in group] 
 for (key, group) in itertools.groupby(vpcs, lambda vpc: vpc['VPCRegion'])}
相关问题