2

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']} )

Ced
  • 1,117
  • 1
  • 8
  • 16
  • 2
    Side note: don't use `map` as a variable name, since there is a built-in function with the same name. Also, in Python, "maps" are called "dictionaries". – voithos Oct 07 '12 at 22:59
  • 2
    In fact, don't use `input` as a variable name either. You guessed it: built-in function. – voithos Oct 07 '12 at 23:01

2 Answers2

7

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
Community
  • 1
  • 1
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
  • 1
    I believe you mean `key, *values` (the syntax of the Extended Iterable Unpacking which you link to). Also I believe you mean `input` rather than `raw_input` (non-existent in python3, which you claim to be writing in). – ninjagecko Oct 07 '12 at 23:03
  • @ninjagecko Great catch on both of those, typo for the former, not looking at the copy/paste for the latter. Corrected. – Gareth Latty Oct 07 '12 at 23:05
2
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)
ninjagecko
  • 88,546
  • 24
  • 137
  • 145