Skip to content Skip to sidebar Skip to footer

Dictionary Comprehension: How Do We Build A Dictionary With Integers As Keys And Tuples As Values?

I have a list of data and they are formated like this: (have more lines below are just part of them) 2 377222 TOYOTA MOTOR CORPORATION TOYOTA PASEO 1994 Y 1994122

Solution 1:

You're creating a new dictionary (not adding to it) each time through the loop (E={A:(B,C,D)for A in A}). Declare your dictionary BEFORE you enter the loop, and add your entry each time THROUGH the loop.

defcreate_database(f)
    """ Returns a populated dictionary.  Iterates over the input 'f'. """
    data = {}
    for line in f:
        # add stuff to data
        key, datum = parse_line(line)
        data[key] = datum
    return data

Solution 2:

By using the csv module (which can be used to process tab delimited files) and possibly operator.itemgetter as a convenience function.

withopen('yourfile') as fin:
    tabin = csv.reader(fin, delimiter='\t')
    # change itemgetter to include the relevant column indices
    your_dict = {int(row[0]): itemgetter(2, 12)(row) for row in tabin}

print your_dict[2]

Post a Comment for "Dictionary Comprehension: How Do We Build A Dictionary With Integers As Keys And Tuples As Values?"