简体   繁体   中英

Converting a text file to python dictionary - one key and multiple values - with exclusion of one field

I have the following tab-delimited text file:

1 John 27 doctor Chicago
2 Nick 33 engineer Washington

I am trying to convert it into a python dictionary where the key is the NAME and the age, career and address are the values. I would like to exclude the rankings (1, 2).

Code:

myfile = open ("filename", "r") 
d = { } 
for line in myfile: 
    x = line.strip().split("\t") 
    key, values = int(x[0]), x[1:] 
    d.setdefault(key, []).extend(values)
print(d)

You can convert it to a dict indexed by name with values in tuples instead:

d = {}
with open('filename', 'r') as myfile:
    for line in myfile:
        _, name, *values = line.strip().split("\t")
        d[name] = values
print(d)

With your sample input, this will output:

{'John': ('27', 'doctor', 'Chicago'), 'Nick': ('33', 'engineer', 'Washington')}

You don't explain what difficulties you face. However, from that sample of tab-delimited text, and you want to have dict like:

{'John': ['27', 'doctor', 'Chicago'], 'Nick': ['33', 'engineer', 'Washington']}

If that's the output you want to reach, then I modified your code a bit.

myfile = open ("filename", "r") 
d = { } 
for line in myfile: 
    x = line.strip().split("\t") 
    key, values = x[1], x[2:] 
    d.setdefault(key, []).extend(values)
print(d)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM