0
Table = u'''A,This is A
B,This is B
C,This is C
D,This is D
E,This is E
F,This is F
G,This is G
H,This is H
I,This is I
J,This is J'''

SearchValue = u'''A
B
C
D
Bang
F
Bang
G
H'''

Table = Table.splitlines()
LineText = {}
for targetLineText in Table:
    LineText[targetLineText.split(',')[0]] = targetLineText.split(',')[1]

SearchValue = SearchValue.splitlines()
for targetValue in SearchValue:
    print LineText[targetValue] if targetValue in LineText else 'Error:' + targetValue

What this code is doing is... It finds value lists from the 'Table' dictionary by keys called 'SearchValue'

I check if the key exists by the following code..

targetValue in LineText

What I want to do to get the value at the same time of the key value existing check. Because I think that performs better.

0

2 Answers 2

2

you should take a look to the dict.get method :

SearchValue = SearchValue.splitlines()
for targetValue in SearchValue:
    print LineText.get(targetValue, 'Error:' + targetValue)
Sign up to request clarification or add additional context in comments.

Comments

1

I've reformatted your code according to the python style guide and added some optimizations:

table = u'''A,This is A
B,This is B
C,This is C
D,This is D
E,This is E
F,This is F
G,This is G
H,This is H
I,This is I
J,This is J'''

search_value = u'''A
B
C
D
Bang
F
Bang
G
H'''

line_text = dict(line.split(",") for line in table.splitlines())

for target_value in search_value.splitlines():
    print line_text.get(target_value, "Error: {0}".format(target_value))

1 Comment

SO NICE!! THANK YOU SO MUCH!! I gotta know about the python style

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.