浏览器的cookie转换为字典格式
将如下的字符串 转换为字典格式的数据
cook_str = 'BIDUPSID=D0727533D7147B7;PSTM=1530348042; BAIDUID=B1005C9BC2EB28; sugstore=0;__cfduid=d0a13458f8ac2a;BD_UPN=12314353;ispeed_lsm=2;BDORZ=B490B5EBF6F3CD402'
# 常规语法实现:
dic1 = {}
res = cook_str.split(';') # 1. 先对字符串进行分割 ";" --> ['BIDUPSID=D0727533D7147B7', 'PSTM=1530348042']
for a in res:
str1 = a.strip().split('=') # 2. 遍历后,再进行分割 "=" --> ['BIDUPSID', 'D0727533D7147B7'] ['PSTM', '1530348042']
dic1[str1[0]] = str1[1] # 3. 利用字典赋值 进行组装
# print(dic1)
# 字典推导式实现
dic2 = { a.strip().split('=')[0]:a.strip().split('=')[1] for a in(cook_str.split(';')) }
print(dic2)
# {'BIDUPSID': 'D0727533D7147B7', 'PSTM': '1530348042', 'BAIDUID': 'B1005C9BC2EB28', 'sugstore': '0', '__cfduid': 'd0a13458f8ac2a', 'BD_UPN': '12314353', 'ispeed_lsm': '2', 'BDORZ': 'B490B5EBF6F3CD402'}
# dic3 = {}
# for a in(cook_str.split(';')): # a是一个字符串 "BIDUPSID=D0727533D7147B7"
# res = a.strip().split('=') # 分割后是['BIDUPSID', 'D0727533D7147B7']
# dic3[res[0]] = res[1] # 字典组装
#
# print(dic3)