I have a list as:
[id, 1234, name, Jack, gender, M, id, 2345,
name, Gary, gender, M, id, 5678 ....]
my desired list will be like this:
[{id:1234, name: Jack, gender: M},
{id:2345, name: Gary, gender: M},
{...........}
]
Zipping them up only returned the last items, so how can I keep all of them?
CodePudding user response:
This works perfectly within the given output.
lst = ['id', 1234, 'name', 'Jack', 'gender', 'M', 'id', 2345,
'name', 'Gary', 'gender', 'M', 'id', 5678]
new_list = []
temp_dict ={}
for a in range(len(lst))[::2]: # range(len(lst))[::2] is a list [0, 2, 4, 6, 8, 10, 12 ...]
if lst[a] == 'id' and a:
new_list.append(temp_dict)
temp_dict = {}
temp_dict[lst[a]]=lst[a 1]
else: # Else execute after the loop exit.
new_list.append(temp_dict)
print(new_list)
Output
[{'id': 1234, 'name': 'Jack', 'gender': 'M'},
{'id': 2345, 'name': 'Gary', 'gender': 'M'},
{'id': 5678}]
CodePudding user response:
You could try:
values = [
'id', 1234, 'name', 'Jack', 'gender', 'M',
'id', 2345, 'name', 'Gary', 'gender', 'M',
'id', 5678, 'name', 'Joe'
]
dicts = [
dict(zip(values[i:i 6:2], values[i 1:i 6:2]))
for i in range(0, len(values), 6)
]
Result:
[{'id': 1234, 'name': 'Jack', 'gender': 'M'},
{'id': 2345, 'name': 'Gary', 'gender': 'M'},
{'id': 5678, 'name': 'Joe'}]
Logic:
- Iterate over each sixth index of
values
(0, 5, 11, ...) - Starting from these indices split the corresponding part of
values
(6 items) into 2 interlaced parts,zip
them, and then build adict
out of the tuples.
The assumption is that values
starts with an 'id'
item.