如何将字典列表转换为值字典

时间:2019-05-13 10:47:17

标签: python list dictionary

我有一个要转换成字典的词典列表。

q2 = [{'ComplainDepartment':'Academic','count':1}, 
      {'ComplainDepartment':'Hostel','count':2}]

将其更改为:

data = {'Academic':1,'Hostel':2}

3 个答案:

答案 0 :(得分:6)

您可以使用生成器理解从每个字典中提取 console.log("Rest2"+this._data);This log is showing Rest2 Udefined ,然后从结果中构建新的values

dictionary

或使用map

dict(d.values() for d in q2)
# {'Academic': 1, 'Hostel': 2}

答案 1 :(得分:2)

尝试一下(字典理解):

{q.get('ComplainDepartment'): q.get('count') for q in q2}

答案 2 :(得分:0)

data = {}
for dictionary in q2:
    data[dictionary["ComplainDepartment"]] = dictionary["count"]