首页 > 解决方案 > 使用临时变量与从字典中重复读取相同的键/值

问题描述

背景:我需要从字典中(完全)读取相同的键/值两次。

问:有两种方式,如下图,

方法 1. 用同一个键读取两次,例如,

sample_map = {'A':1,}
...
if sample_map.get('A', None) is not None:
    print("A's value in map is {}".format(sample_map.get('A')))

方法 2. 读取一次并将其存储在局部变量中,例如,

sample_map = {'A':1,}
...
ret_val = sample.get('A', None)
if ret_val is not None:
    print("A's value in map is {}".format(ret_val))

哪种方式更好?他们的优点和缺点是什么?

请注意,我知道print()可以自然地处理ret_val. None这是一个假设示例,我只是将其用于说明目的。

标签: pythondictionarycode-duplicationanti-patterns

解决方案


在这种情况下,我也不会使用。你真正感兴趣的是是否A是一个有效的密钥,并且提出的KeyError(或缺乏的)__getitem__会告诉你它是否是。

try:
    print("A's value in map is {}".format(sample['A'])
except KeyError:
    pass

或者当然,有些人会说块中的代码太多try,在这种情况下方法2会更好。

try:
    ret_val = sample['A']
except KeyError:
    pass
else:
    print("A's value in map is {}".format(ret_val))

或您已有的代码:

ret_val = sample.get('A')  # None is the default value for the second argument
if ret_val is not None:
    print("A's value in map is {}".format(ret_val))

推荐阅读