首页 > 编程语言 >python 数组字典转换

python 数组字典转换

时间:2022-12-22 16:44:32浏览次数:43  
标签:tmp arr name python age template else 数组 字典

将提交的数组字段 一个字典


	[
		{
			"name": "name1",
			"age": "1",
			
		},
		{
			"name": "name2",
			"age": "2",
		}
	]


# 变成
{
			"name": "name1,name2",
			"age": "1,2",
			
}

直接上代码

t = {
        "name": "",
        "age": "",
    }
    for v in d:
        template = "%s,%s"
        t['name'] = (template % (t['name'], v['name'])) if t['name'] else v['name']
        t['age'] = (template % (t['age'], v['age'])) if t['age'] else v['age']

将字段变成数组

tmp_arr = []
    for k, v in t.items():
        for idx, term in enumerate(v.split(",")):
            if len(tmp_arr) > idx:
                tmp_arr[idx][k] = term
            else:
                tmp_arr.append({k: term})

标签:tmp,arr,name,python,age,template,else,数组,字典
From: https://www.cnblogs.com/guanchaoguo/p/16999093.html

相关文章