python - 如何将具有多个键值的字典数组转换为具有单个键值的字典?

标签 python

我有以下输入数据

options_d = [{'id': 36, 'label': 'Angular'},
 {'id': 37, 'label': 'Java'},
 {'id': 38, 'label': 'PHP'},
 {'id': 39, 'label': 'Python'},
 {'id': 40, 'label': 'C#'},
 {'id': 41, 'label': 'C'},
 {'id': 42, 'label': '.NET'},
 {'id': 43, 'label': 'Ruby'},
 {'id': 44, 'label': 'Rails'},
 {'id': 45, 'label': 'OS-Linux'},
 {'id': 55, 'label': 'Maschinenbau'},
 {'id': 56, 'label': 'Automotive'},
 {'id': 57, 'label': 'Engineering'}]

我想把它变成

{36: 'Angular',
 37: 'Java',
 38: 'PHP',
 39: 'Python',
 40: 'C#',
 41: 'C',
 42: '.NET',
 43: 'Ruby',
 44: 'Rails',
 45: 'OS-Linux',
 55: 'Maschinenbau',
 56: 'Automotive',
 57: 'Engineering'}

到目前为止我所做的是

skillsmap_person = {}
for option in options_d:
    skillsmap_person[option['id']] = option['label']

它有效。但是,有没有我可以使用的单行字典分配解决方案?

有什么想法吗?

最佳答案

使用 dict comprehensions 创建 dictionary -

options_dict = {i['id']:i['label'] for i in options_d}
print(options_dict)
    {36: 'Angular',
     37: 'Java',
     38: 'PHP',
     39: 'Python',
     40: 'C#',
     41: 'C',
     42: '.NET',
     43: 'Ruby',
     44: 'Rails',
     45: 'OS-Linux',
     55: 'Maschinenbau',
     56: 'Automotive',
     57: 'Engineering'}

关于python - 如何将具有多个键值的字典数组转换为具有单个键值的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54415739/

相关文章:

python - groupby - TypeError 'DataFrame' 对象不可调用

python - scrapy 登录与 InitSpider 相关的问题

python - 检测损坏数据的算法?

python - 引用错误版本的 Python 的库

python - Eclipse 随机用空格替换制表符

python - for 循环连接字符串

python - Pandas 数据框条件列更新

python - 这个闭包有没有更 'pythonic'的写法?

python - 尝试绘制任意 3d 函数的图形时出错

python - Django 查询集上的 random.sample : How will sampling on querysets affect performance?