python3 下列表与字典转换

时间:2022-02-16 03:04:15

在写爬虫的时候,经常需要处理cookie,requests库里的cookie是dict,但是headers['cookie']却是一个key=value的字符串。

下面是几个用推导式实现的转换函数,供大家参考。

#coding=utf-8
#create by :joshua zou
#create date :2018.5 import logging #key=value列表转换成cookie字典
def cookie_list_2_dict(cookli):
if not isinstance(cookli,list):
logging.error('error list param...')
return {} return {item.split('=')[0]:item.split('=')[1] for item in cookli} #heads['cookie']字符串转换成cookie字典
def cookie_str_2_dict(cookstr):
if not isinstance(cookstr,str):
logging.error('error str param...')
return {} cookstr = cookstr.split(';')
return cookie_list_2_dict(cookstr) #cookie字典转换成key=value列表
def cookie_dict_2_list(cookdi):
if not isinstance(cookdi,dict):
logging.error('error dict param...')
return []
cookli = ["%s=%s" %(key,value) for key,value in cookdi.items()]
return cookli #cookie字典转换成heads['cookie']字符串
def cookie_dict_2_str(cookdi):
if not isinstance(cookdi,dict):
logging.error('error dict param...')
return ""
cookli = cookie_dict_2_list(cookdi)
return ';'.join(cookli) if __name__=='__main__':
cookies = {'AST': '1525005900068b4106e25d4', '___bz': '708632|41171989|2b7718|aladin2_freexx', 'platform': 'H5'}
cookli = cookie_dict_2_list(cookies)
cookstr = cookie_dict_2_str(cookies)
print('cook list',cookli)
print('cook str',cookstr) cookdi1 = cookie_str_2_dict(cookstr)
cookdi2= cookie_list_2_dict(cookli)
print('cook dict 1',cookdi1)
print('cook dict 2',cookdi2)

输出结果:

cook list ['AST=1525005900068b4106e25d4', '___bz=708632|41171989|2b7718|aladin2_freexx', 'platform=H5']
cook str AST=1525005900068b4106e25d4;___bz=708632|41171989|2b7718|aladin2_freexx;platform=H5
cook dict 1 {'AST': '1525005900068b4106e25d4', '___bz': '708632|41171989|2b7718|aladin2_freexx', 'platform': 'H5'}
cook dict 2 {'AST': '1525005900068b4106e25d4', '___bz': '708632|41171989|2b7718|aladin2_freexx', 'platform': 'H5'}

以上。。。