Somputer
Somputer

Reputation: 1283

split list two part in python using dictionary

i want to split list like this

[{'Age': '23', 'Name': 'John'}, {'Age': '43', 'Name': 'Apple'}, {'Age': '13', 'Name': 'Alice'}]

this is my code

temp_list=["John","Apple","Alice","23","43","13"]
temp_dict={'Name':'','Age':''}
final_list=[]
for 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 i do?

Upvotes: 1

Views: 74

Answers (2)

Dieselist
Dieselist

Reputation: 945

generate a structure you've specified in your question:

>>> [dict(zip(("Age", "Name"), x)) for x in zip(temp_list[3:], temp_list[:3])]
[{'Age': '23', 'Name': 'John'}, {'Age': '43', 'Name': 'Apple'}, {'Age': '13', 'Name': 'Alice'}]

Upvotes: 1

JuniorCompressor
JuniorCompressor

Reputation: 20015

You can use the 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) you can use:

final_list = dict(zip(temp_list[:n // 2], temp_list[n // 2:]))

Upvotes: 2

Related Questions