2

I have created a dictionary which I have assigned the first element of a list as a key. I would like to append the rest of the elements as values to the dictionary:

file_a contains tab delimited fields.

a = {}
for line in file_a.readlines():
    split_line = line.strip().split('\t')
    a[split_line[0]] = []
    a[split_line[0]].append(split_line[::-1]) # append from second to last element to the list

The ::-1 appends all the elements. I need to append all elements except the first one (as that is used as a key). Any help will be appreciated.

e.g. if fields are: X\t1\t2\t3 I would like the hash to be:

'X': ['1', '2', '3']
Mark
  • 365
  • 3
  • 9
  • 18

2 Answers2

5

The Python slice syntax is alist[start:end:step]. So, with your slice ::-1, you are just reversing the list. If you want the second element to the last, the correct slice would be alist[1:]

a = {}
for line in file_a.readlines():
    split_line = line.strip().split('\t')
    a[split_line[0]] = split_line[1:]
2
a = {}
for line in file_a:
    split_line = line.strip().split('\t')
    a[split_line[0]] = split_line[1:]

You slicing expression split_line[::-1] evaluates to split_line reversed, because the third parameter is the step (-1 in this case). You want to start at element 1 and go all the way to the end, with the default step of 1. Check this answer for more on slice notation.

Community
  • 1
  • 1
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175