split list two part in python using dictionary -
i want split list this
[{'age': '23', 'name': 'john'}, {'age': '43', 'name': 'apple'}, {'age': '13', 'name': 'alice'}]
this code
temp_list=["john","apple","alice","23","43","13"] temp_dict={'name':'','age':''} final_list=[] temp in temp_list: temp_dict['name']=temp temp_dict['age']=temp final_list.append(temp_dict) temp_dict={'name':'','age':''} print final_list
how can do?
you can use following dict comprehension:
final_list = dict(zip(temp_list[:3], temp_list[3:]))
example:
>>> temp_list=["john","apple","alice","23","43","13"] >>> final_list = dict(zip(temp_list[:3], temp_list[3:])) >>> final_list {'john': '23', 'apple': '43', 'alice': '13'}
in general, if n = len(temp_list)
can use:
final_list = dict(zip(temp_list[:n // 2], temp_list[n // 2:]))
Comments
Post a Comment