0

I have a result dictionary with pre-defined keys that should be populated based on slices of an array without explicitly accessing the dictionary keys, below is an example of my approach

my_list = ['a','b','c','d','e']
my_dict = {'first_item':'', 'middle_items':'','last_item':''}

for key in my_dict.keys():
    value = my_list.pop()
    my_dict.update({k:''.join(value)})

This approach obviously does not work because pop does not slice the array. And if I want to use slicing, I will have to explicitly access the dictionary variables and assign the corresponding list slices.

I have tried using the list length to slice through the list, but was unable to find a general solution, here is my other approach

for key in my_dict.keys():
    value = ''.join(my_list[:-len(my_list)+1])
    del my_list[0]
    my_dict.update({k:v})

How can I slice a list in a general way such that it splits into a first item, last item, and middle items? below is how the updated dictionary should look like

my_dict = {'first_item':'a', 'middle_items':'b c d','last_item':'e'}

Edit: if I use [0],[1:-1], and [-1] slices then that means that I will have to access each dictionary key individually and update it rather than loop over it (which is the desired approach)

ramez
  • 321
  • 3
  • 22

2 Answers2

4

If you are using python 3 then you should try this idiom:

my_list = ['a','b','c','d','e']
first_item, *middle_items, last_item = my_list

my_dict = dict(
    first_item=first_item,
    middle_items=' '.join(middle_items),
    last_item=last_item
)
print(my_dict)
# {'last_item': 'e', 'middle_items': 'b c d', 'first_item': 'a'}
nicholishen
  • 2,602
  • 2
  • 9
  • 13
  • Thanks! slightly modifying your answer helped me reach the solution, I managed to append the dictionary by extending the unpacked list items and zipping the new list to the dictionary keys. (for anyone who cares why I'm going with this approach, it is because I'm reading the dict from a general config file, and I do not want to hard-code the dict keys in my code) – ramez Dec 18 '18 at 22:11
1

To get a slice of my_list, use the slice notation.

my_list = ['a', 'b', 'c', 'd', 'e']

my_dict = {
    'first_item': my_list[0],
    'middle_items': ' '.join(my_list[1:-1]),
    'last_item': my_list[-1]
}

Output

{'first_item': 'a',
 'middle_items': 'b c d',
 'last_item': 'e'}
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73