Reputation: 1253
I have a list like this,
main_list = [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14]
I have another list like this,
sec_list = [0, 5, 10]
Now, I need an output dictionary like this:
extract_dict = {0:[1,2,3,4], 5:[6,7,8,9], 10:[11,12,13,14]}
My key will be for the dictionary is from sec_list
and values are from main_list
.
I was trying to select the range of values using sec_list
values like this,
extract_dict = {}
for i in range(len(sec_list)-1):
extract_dict[sec_list[i]] = main_list[sec_list[i]:sec_list[i+1]]
I got an output like this, which is not what I like,
{0: [1, 2, 3, 4, 6], 5: [7, 8, 9, 11, 12]}
How can I achieve my results?
Upvotes: 0
Views: 33
Reputation: 22776
You can achieve this using the following:
main_list = [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14]
sec_list = [0, 5, 10]
extract_dict = {}
for i, k in enumerate(sec_list):
if i < len(sec_list) - 1:
p = sec_list[i + 1]
extract_dict[k] = main_list[k - i : (k - i) + p - k - 1]
#[k - i : p - i - 1] <== can be simplified to
else:
extract_dict[k] = main_list[k - i : ]
print(extract_dict)
Output:
{0: [1, 2, 3, 4], 5: [6, 7, 8, 9], 10: [11, 12, 13, 14]}
Upvotes: 1