Soumya
Soumya

Reputation: 5412

Handling file reading and multiple values to a key in dictionary

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

Upvotes: 2

Views: 2279

Answers (2)

Muhammad Alkarouri
Muhammad Alkarouri

Reputation: 24662

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.

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 881595

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

Upvotes: 0

Related Questions