把python列表中相同的键不同值的数据逐个添加到字典中

 原字符串为str,原意将前端发送过来的post请求体中的数据单独匹配出来。

1,使用正则表达式根据&符号切割成数据单独的列表

格式如: [user_name = gf,sex = 1,hobby = 1,hobby = 2,hobby = 3,file ='',about = fdg,jiguan = 1]

2,使用for循环格式,将列表中的内容遍历出来,并添加到字典中【注意,需要提前在外部建立一个空字典】

3,使用in方法,判断字典中是否存在这个对应的键,如果存在,则就是相同的键 需要把值进行拼接重新赋值给这个键;如果不存在,则直接把遍历的列表中的键和值 添加到字典中。以下代码可以直接拷贝运行。

import re

str='''user_name=gf&pwd=&sex=1&hobby=1&hobby=2&hobby=3&file=&about=fdg&jiguan=1'''
print(str)
data_finaall = re.findall('(.*?=.*?)&', str)
split_data = re.split('&', str)
print(split_data)
print(data_finaall)
data_dict=dict()
for key in split_data:
    # user_name = gf
    # pwd =
    # sex = 1
    # hobby = 1
    # hobby = 2
    # hobby = 3
    # file =
    # about = fdg
    # jiguan = 1
    split_data_key = re.split('=', key)
    #================================================================
    # print(split_data_key)
    # ['user_name', 'gf']
    # ['pwd', '']
    # ['sex', '1']
    # ['hobby', '1']
    # ['hobby', '2']
    # ['hobby', '3']
    # ['file', '']
    # ['about', 'fdg']
    # ['jiguan', '1']
    #================================================================
    if split_data_key[0] in data_dict:
        data_dict[split_data_key[0]]=split_data_key[1]+','+data_dict[split_data_key[0]]
    else:
        data_dict[split_data_key[0]]=split_data_key[1]

print(data_dict)

原结果hobby属性会重复只取一个,经过此处理之后结果符合预期!

输出结果:

函数输出的内容!!! {'user_name': 'gf', 'sex': '1', 'hobby': '3,2,1', 'pwd': '', 'jiguan': '1', 'about': 'fdg', 'file': ''}

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值