tags:

views:

57

answers:

2

How can I code to read the first line from a file and put it as a key value of a dictionary and keep reading next values in a iterative manner and put them as the values to the particular key they fall into in the file. Like example:

Item Quality Cost Place

Ball     1        $12    TX
Umbrella 5        $35    NY
sweater  89       $100   LA

So here, the representation is my file. When I read, I want the dictionary to be created as in the things in bold go as keys and when i keep reading lines below that, I would have them going as multiple values in the respective keys.

thanks

+1  A: 

Looks like you are describing a csv file with a space delimiter. Something like this should work (from the Python help).

>>> import csv
>>> spamReader = csv.reader(open('eggs.csv', 'rb'), delimiter=' ', quotechar='|')
>>> for row in spamReader:
...     print ', '.join(row)
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

In fact, the csv.DictReader would be better in order to have each row as a dictionary with keys defined by the first row.

I am assuming that there is a newline inserted after each group of values.

Edit: Using the example above, we get:

In [1]: import csv

In [2]: f = csv.DictReader(open('test.txt', 'r'), delimiter = ' ', skipinitialspace = True)

In [3]: for row in f: print row

{'Item': 'Ball', 'Cost': '$12', 'Quality': '1', 'Place': 'TX'}
{'Item': 'Umbrella', 'Cost': '$35', 'Quality': '5', 'Place': 'NY'}
{'Item': 'sweater', 'Cost': '$100', 'Quality': '89', 'Place': 'LA'}

Passing the parameter skipinitialspace = True to the DictReader is needed to be able to get rid of multiple spaces without creating spurious entries in each row.

Muhammad Alkarouri
i am sorry ..it is not been shown properly here but its not a csv file..Ita a file having tabular format like the bold ones are headers and the rest are values under them
Compuser7
Compuser7. Yes I got that. That is why you would use `delimiter=' '. Python's csv works for tabular formats as well if you choose the right delimiter.
Muhammad Alkarouri
@Compuser7, I have reformatted your Q to show the file properly -- and my A assumes arbitrary numbers of spaces as separators, just like your file appears to have.
Alex Martelli
@Muhammad, doesn't work when _multiple_ spaces are "the separator" (e.g. to align columns in a visually pretty way, as seems to be the case for the OP's example file).
Alex Martelli
@Alex: see the example added in the answer. You need `skipinitialspace`.
Muhammad Alkarouri
A: 

You can't have "multiple values" for a given key, but you can of course have one value per key that's a list.

For example (Python 2.6 or better -- simply because I use the next function for generality rather than methods such as readline, but you can of course tweak that!):

def makedictwithlists(f):
    keys = next(f).split()
    d = {}
    for k in keys: d[k] = []
    for line in f:
        for k, v in zip(keys, line.split()):
            d[k].append(v)
    return d
Alex Martelli