Dictionary Comprehension: How do we build a dictionary with integers as keys and tuples as values?

好久不见. 提交于 2020-03-26 11:03:29

问题


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   19941226    N   0   0   PARKING BRAKE:CONVENTIONAL  SAN JOSE        CA  JT2EL45U5R0 19950103    19950103        1   PARKED ON FLAT SURFACE EMERGENCY BRAKING ENGAGED VEHICLE ROLLED REARWARD.  TT   EVOQ                                                                                                    V           
1   958164  TOYOTA MOTOR CORPORATION    TOYOTA  LAND CRUISER    1994        19941223    N   0   0   SERVICE BRAKES, HYDRAULIC:ANTILOCK  ARNOLD          CA  JT3DJ81W8R0 19950103    19950103            ABS SYSTEM FAILURE, AT 20MPH.  TT   EVOQ                                                                                                    V
46  958153  DAIMLERCHRYSLER CORPORATION DODGE   CARAVAN 1987        19940901    N   0   0   EQUIPMENT:MECHANICAL:CARRIER/RACK   CORBETT         OR  2B4FK4130HR 19950103    19950103        1   CABLE ATTACHMENT THAT SECURES THE SPARE TIRE BROKE WHILE DRIVING.  TT   EVOQ                                                                                                    V   
98  958178  GENERAL MOTORS CORP.    GMC SAFARI  1994        19941223    N   0   0   SERVICE BRAKES, HYDRAULIC:FOUNDATION COMPONENTS MILAN           MI  1GDDM19W4RB 19950103    19950103        1   BRAKES FAILED DUE TO BATTERY MALFUNCTIONING WHEN TOO MUCH POWER WAS DRAWN FROM BATTERY FOR RADIO.   TT  EVOQ                                                                                                    V   

What is the best way to create a dictionary using index(1) the integer as keys and a tuple of any other 2 elements in the sentence as values? The desired output should be like this:

function(filename)[2]
('TOTOTA MOTOR CORPORATION','19941226','SAN JOSE','CA')

Here is what I have right now and I was trying to put them all into a dictionary first but it wont iterate through he entire list instead it just returns the elements of a single line. What went wrong with my code? or How do I at least accomplish the first step - putting them all in a dictionary?

def function(filename):
    with open filename as FileObject:
        A=[]
        for lines in FileObject:
            B=[line.split("\t")[0]]
            A+=B
            C=[line.split("\t")[2]]
            A=A+B+C
            D=[line.split("\t")[12]]
            A=A+B+C+D
            E={A:(B,C,D)for A in A}
    return E
print function(filename)

回答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.

def create_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



回答2:


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

with open('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]


来源:https://stackoverflow.com/questions/13128440/dictionary-comprehension-how-do-we-build-a-dictionary-with-integers-as-keys-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!