user_dict = {} users = ["baoshan1", "baoshan2", "baoshan3","baoshan1", "baoshan2", "baoshan2"] for user in users: if user not in user_dict: user_dict[user] = 1 else: user_dict[user] += 1 print(user_dict) user_dict = {} users = ["baoshan1", "baoshan2", "baoshan3","baoshan1", "baoshan2", "baoshan2"] for user in users: user_dict.setdefault(user, 0) user_dict[user] += 1 print(user_dict) # 不需要做if else的判断 # 效率高,少一次user_dict的查询操作 from collections import defaultdict user_dict = defaultdict(int) users = ["baoshan1", "baoshan2", "baoshan3","baoshan1", "baoshan2", "baoshan2"] for user in users: user_dict[user] += 1 print(user_dict) # defaultdict的好处,传递可调用的对象例如int、list、函数等