Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - get subset from 2nd, to last element

I have a bunch of strings, all on one line, separated by a single space. I would like to store these values in a map, with the first string as the key, and a set of the remaining values. I am trying

map = {}
input =  raw_input().split()
map[input[0]] = input[1:-1]

which works, apart from leaving off the last element. I have found

map[input[0]] = input[1:len(input)]

works, but I would much rather use something more like the former

(for example, input is something like "key value1 value2 value3" I want a map like
{'key' : ['value1', 'value2', 'value3']}
but my current method gives me
{'key' : ['value1', 'value2']} )

like image 917
Ced Avatar asked Nov 19 '25 06:11

Ced


1 Answers

That's because you are specifying -1 as the index to go to - simply leave the index out to go to the end of the list. E.g:

input[1:]

See here for more on the list slicing syntax.

Note an alternative (which I feel is far nicer and more readable), if you are using Python 3.x, is to use extended iterable unpacking:

key, *values = input().split()
map[key] = values
like image 166
Gareth Latty Avatar answered Nov 20 '25 19:11

Gareth Latty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!