在python中获取字典值的最佳性能

2024-06-16 15:02:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这个代码的作用是。。。 它通过名为“SearchValue”的键从“Table”字典中查找值列表

我通过下面的代码检查密钥是否存在。。在

^{pr2}$

我要做的是在键值存在检查的同时获取值。因为我觉得这样做更好。在


Tags: 代码inforifistablethissplit
2条回答

您应该看看dict.get方法:

SearchValue = SearchValue.splitlines()
for targetValue in SearchValue:
    print LineText.get(targetValue, 'Error:' + targetValue)

我根据the python style guide重新格式化了代码,并添加了一些优化:

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))

相关问题 更多 >