dict = {'evaporation': {'释义': '蒸发', '词性': 'n'}, 'carpenter': {'释义': '木匠', '词性': 'n'}}
常规做法通常是这样,即先验证 key 是否在字典中,如果不存在,则加入字典:
if 'future' not in dict: dict['future']={'释义': '未来', '词性': 'n'}
我们可以使用字典的 setdefault() 方法,直接实现上述功能:
dict.setdefault('future', {'释义': '未来', '词性': 'n'})
运行结果:
{‘evaporation’: {‘释义’: ‘蒸发’, ‘词性’: ‘n’}, ‘carpenter’: {‘释义’: ‘木匠’, ‘词性’: ‘n’}, ‘future’: {‘释义’: ‘未来’, ‘词性’: ‘n’}}
传递给 setdefault 方法的第一个参数是要检查的键。第二个参数是如果该键不存在需要设置的默认值。如果该键存在,该方法会直接返回键所对应的值:
carpenter = dict.setdefault('carpenter', '未收入本词典') print('carpenter = ' + str(carpenter))
运行结果:
carpenter = {‘释义’: ‘木匠’, ‘词性’: ‘n’}
利用 setdefault 方法,我们可以很方便地统计出,一个字符串所拥有字符出现次数:
content = '美国国家航空航天局(NASA)局长吉姆·布莱登斯汀日前表示,如果对太空探索技术公司(SpaceX)载人“龙”飞船进行的测试结果是肯定的话,该公司的飞船将最早于明年把美国宇航员送往国际空间站。迄今为止,SpaceX从未将人类送入太空,一直运送的只有货物。' count = {} for char in content: count.setdefault(char, 0) count[char] = count[char] + 1 print(count)
运行结果:
{‘美’: 2, ‘国’: 4, ‘家’: 1, ‘航’: 3, ‘空’: 4, ‘天’: 1, ‘局’: 2, ‘(‘: 2, ‘N’: 1, ‘A’: 2, ‘S’: 3, ‘)’: 2, ‘长’: 1, ‘吉’: 1, ‘姆’: 1, ‘·’: 1, ‘布’: 1, ‘莱’: 1, ‘登’: 1, ‘斯’: 1, ‘汀’: 1, ‘日’: 1, ‘前’: 1, ‘表’: 1, ‘示’: 1, ‘,’: 4, ‘如’: 1, ‘果’: 2, ‘对’: 1, ‘太’: 2, ‘探’: 1, ‘索’: 1, ‘技’: 1, ‘术’: 1, ‘公’: 2, ‘司’: 2, ‘p’: 2, ‘a’: 2, ‘c’: 2, ‘e’: 2, ‘X’: 2, ‘载’: 1, ‘人’: 2, ‘“’: 1, ‘龙’: 1, ‘”’: 1, ‘飞’: 2, ‘船’: 2, ‘进’: 1, ‘行’: 1, ‘的’: 4, ‘测’: 1, ‘试’: 1, ‘结’: 1, ‘是’: 1, ‘肯’: 1, ‘定’: 1, ‘话’: 1, ‘该’: 1, ‘将’: 2, ‘最’: 1, ‘早’: 1, ‘于’: 1, ‘明’: 1, ‘年’: 1, ‘把’: 1, ‘宇’: 1, ‘员’: 1, ‘送’: 3, ‘往’: 1, ‘际’: 1, ‘间’: 1, ‘站’: 1, ‘。’: 2, ‘迄’: 1, ‘今’: 1, ‘为’: 1, ‘止’: 1, ‘从’: 1, ‘未’: 1, ‘类’: 1, ‘入’: 1, ‘一’: 1, ‘直’: 1, ‘运’: 1, ‘只’: 1, ‘有’: 1, ‘货’: 1, ‘物’: 1}