list of dict 转换成 dict of list 字典形 列表 转换 列表形 字典 in Python

list_of_dict

list_of_dict = {
    "title":['title1','title2','title3','title4','title15'],
    "author":['author1','author2','author3','author4','author5'],
    "postdate":['2018-7-19','2018-7-20','2018-7-21','2018-7-22','2018-7-23'],
    "tags":['sex','man','female','health','social']
}

代码

dict_of_list = []
for key in list_of_dict :                                   #TODO 遍历 list_of_dict 的key ['title','author','postdata']
    for num, value in enumerate(list_of_dict[key]):         #TODO 遍历 当前 key下 value 的列表
        if dict_of_list .__len__() < list_of_dict [key].__len__():
            dict_of_list .append({
                key: value
            })
        elif dict_of_list .__len__() == list_of_dict [key].__len__():
            dict_of_list [num][key] = value


>>>pprint(dict_of_list)
>
[{'author': 'author1',
  'postdate': '2018-7-19',
  'tags': 'sex',
  'title': 'title1'},
 {'author': 'author2',
  'postdate': '2018-7-20',
  'tags': 'man',
  'title': 'title2'},
 {'author': 'author3',
  'postdate': '2018-7-21',
  'tags': 'female',
  'title': 'title3'},
 {'author': 'author4',
  'postdate': '2018-7-22',
  'tags': 'health',
  'title': 'title4'},
 {'author': 'author5',
  'postdate': '2018-7-23',
  'tags': 'social',
  'title': 'title15'}]

猜你喜欢

转载自blog.csdn.net/qq_33042187/article/details/81108986