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'}]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章