Reputation: 1217
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']}
)
Upvotes: 2
Views: 9118
Reputation: 89097
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
Upvotes: 7
Reputation: 91159
myDict = {}
for line in lines:
tokens = line.split()
map[tokens[0]] = tokens[1:]
Alternatively:
def lineToPair(line):
tokens = line.split()
return tokens[0],tokens[1:]
myDict = dict(lineToPair(x) for x in lines)
Upvotes: 2