Skip to main content
 首页 » 编程设计

python之从嵌套列表生成字典,Python 3.6

2025年05月04日14xing901022

我有以下列表:

dimensionList = [{'key': 2109290, 'id': 'R', 'name': 'Reporter', 'isGeo': True, 'geoType': 'region'},  
         {'key': 2109300, 'id': 'C', 'name': 'Commodity', 'isGeo': False, 'geoType': None},  
         {'key': 2109310, 'id': 'P', 'name': 'Partner', 'isGeo': True, 'geoType': 'region'},  
         {'key': 2109320, 'id': 'TF', 'name': 'Trade Flow', 'isGeo': False, 'geoType': None},  
         {'key': 2109330, 'id': 'I', 'name': 'Measure', 'isGeo': False, 'geoType': None}] 

我想从这个列表创建字典

需要“id”的值作为字典的 Id 和“name”的值作为字典的值

预期结果:-

ResultsDict = {'R':'Reporter', 'C':'Commodity', 'P':'Partner', 'TF':'Trade Flow', 'I':'Measure'} 

请您参考如下方法:

使用字典理解:

d = {x['id']:x['name'] for x in dimensionList} 
print (d) 
{'R': 'Reporter', 'C': 'Commodity', 'P': 'Partner', 'TF': 'Trade Flow', 'I': 'Measure'}