0

I am a python newbie. I have an input file like this:

1 2 3 4 /a/
5 6 7 8 /b/
9 0 1 2 /c/
3 4 5 6 /d/

I need to read the file and store the numbers in a dictionary, say d, but use the words in the last column as index. For instance I'd like

d['aa'] = 1, 
d['ab'] = 2, 
d['ac'] = 3 , 
d['ad'] = 4 
...
ahb65
  • 191
  • 2
  • 13

2 Answers2

3

That's not really how dictionaries work. A dictionary is basically a hash table. The keys work like a set; in that duplicate entries aren't allowed. I think what you are trying to do is something like:

data = """1 2 3 4 /a/
5 6 7 8 /b/
9 0 1 2 /c/
3 4 5 6 /d/"""

result = {}
for line in data.split("\n"):
    *numbers, index = line.split(" ")
    index = index.replace("/", "")
    result[index] = numbers
print(result)

The dictionary indexes are not ordered. If you want to keep their order, you can always store that also:

indexes_ordered = []
...
indexes_ordered.append(index)

Or check out this question to discover sorting.

Lastly, to get your values, you can iterate through the keys:

for key in result:
    print(result[key])

Or, at your option, change result to indexes_ordered. You can do things to your ordered lists for each dictionary entry through any of the multitudinous forms of list comprehension.

For bonus points, you can have dictionary entries point to other dictionary entries:

x = {}
x[0] = 1
x[1] = 2
x[2] = 3
x[3] = "yay!"
result = 0
y = 0
while y in x: y = x[y]
result = y
print(result)

To get what you describe in your edited question, you would do something like:

another_result = {}
a = ord('a')
for key in result:
    x = result[key]
    for n in range(len(x)):
        another_result[key + chr(a+n)] = x[n]
for key in another_result: print(key, another_result[key])

Comment if you have any questions.

Community
  • 1
  • 1
motoku
  • 1,571
  • 1
  • 21
  • 49
  • Thank you very much for you suggestion! How about having a unique index for each number obtained from concatenation of the words in the column and row? For instance instead of d['a']['b'] we have d['ab'] and so on. – ahb65 Mar 01 '15 at 04:57
  • I know you have put more than enough time on this. But do you have any idea how I can achieve that? – ahb65 Mar 01 '15 at 05:01
  • @ahb65 I appended my answer. – motoku Mar 01 '15 at 05:09
0

Here is the solution:

d={};k=0;key=[];val=""
tFile=open("inputFile",'r')
dat=tFile.readlines()
for i in range(len(dat)):
    val += a[i].split('/')[0] # store all the numbers in val
    key.append(a[i].split('/')[1].strip()) # store letters in key
val = " ".join(val.split()) # remove extra white spaces
#merge keys and values into a single dictionary
for i in key:
    for j in key:
        d[i+j]=val.split(" ")[k].strip()
        k+=1
return d
ahb65
  • 191
  • 2
  • 13