2

I am looking for a lookup function for print corresponding names. I have a list file

a Chief manager
b Assistant general manager
c general manager
D CTO
E CEO

I have a variable “user” in my script I want to check the variable in first column, if the value match then print corresponding name

Eg if “user”==a then print “Chief manager”

1

2 Answers 2

5

Using a dictionary will be easier.

d = { 'a': 'Chief Manager', 'b': 'Assistant General Manager', 'c': 'General Manager', 'D': 'CTO', 'E': 'CEO' }
user = 'a'
print(d[user])
# Chief Manager

To load that file into a dictionary, you could do this:

with open('/path/to/my/file') as myFile:
    d = dict(line.strip().split(None, 1) for line in myFile)

print(d['a'])
# Cheif manager

If you want to parse a CSV file, it depends on how the file is actually formatted. If it looked like this:

a,"Cheif manager"
b,"Assistant general manager"
c,"general manager"
D,"CTO"
E,"CEO"

You could read that in like this:

from csv import reader
d = dict(row for row in reader(open('/path/to/my/file'), delimiter=',', quotechar='"'))
print(d['a'])
# Cheif manager
Sign up to request clarification or add additional context in comments.

10 Comments

That list is a file which frequently change.
@Albin: Well, basically you'll want to parse that file and put the contents into the dictionary. It's not going to be much easier working with the raw text in the file.
@jeff Thanks. what about a csv file ?
@Albin: A CSV formatted file is just another file format. It shouldn't be much different than if it was in the format that you have shown in your question. Using the csv module can make parsing and creating the dictionary relatively easy.
@martineau: I agree, though Albin did ask about it so I was inclined to provide an example but without having to make up additional data.
|
1

Assuming that the first column would be unique in someway, your first task would be to construct a dictonary with keys from the first column and values from the second.

to construct the dictionary, try it in the following manner.

org_dict = dict()
line = 'a Chief manager'
key,value = line.split(None,1)
org_dict[key] = value

Now to get each line from your file, you can open the file and read then line by line.

with open('myfile') as f:
    for line in f:
        # process your line

1 Comment

Try fields = line.split(None, 1) to split the line into the letter and the complete name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.