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

标签 python python-3.x pandas dictionary

我有以下列表:

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'}

关于python - 从嵌套列表生成字典,Python 3.6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53670447/

相关文章:

python - numpy fft 中的意外振幅

Python多行正则表达式忽略字符串中的n行

python /MyPy : How to annotate a method that can return one of several different types of objects?

python - 如何在Python中使用列表理解

python - 如何处理 "Incompatible return value type (got overloaded function)"问题

python - 如何从表中创建对

python - 未找到 Psycopg2 图像

python - 我可以对 sklearn 进行对数回归吗?

python - 等效于 Python Pandas 中的 R rbind.fill

python - 从循环创建数据框