# 字典与集合那些事儿

## 字典和集合那些基础操作

### 先说字典

``````my_dict = {}
my_dict["A"] = "A"
my_dict["B"] = "B"
my_dict["C"] = "C"
my_dict["D"] = "D"

for key in my_dict:
print(key)``````

``````my_dict = {}
my_dict["A"] = "A"
my_dict["B"] = "B"
my_dict["C"] = "C"
my_dict["D"] = "D"

print(my_dict["F"])``````

``````Traceback (most recent call last):
File ".\demo.py", line 7, in
print(my_dict["F"])
KeyError: 'F'``````

``print(my_dict.get("F","None"))``

### 再聊集合

``````my_set = {"A","B","C"}
print(my_set[0])``````

## 字典与集合的排序

``````my_set = {"A","B","C"}
print(my_set.pop())``````

``````my_dict = {}
my_dict["A"] = "4"
my_dict["B"] = "3"
my_dict["C"] = "2"
my_dict["D"] = "1"
sorted_dict = sorted(my_dict.items(),key=lambda x:x[1])
print(sorted_dict)``````

``[('D', '1'), ('C', '2'), ('B', '3'), ('A', '4')]``

## 字典与集合的效率问题

``````def find_unique_weight(students):
# 声明一个统计列表
unique_list = []
# 循环所有学生数据
for id, weight in students:
# 如果体重没有在统计列表中
if weight not in unique_list:
# 新增体重数据
unique_list.append(weight)
# 计算列表长度
ret = len(unique_list)
return ret

students = [
(1, 90),
(2, 90),
(3, 60),
(4, 100)
]
print(find_unique_weight(students))``````

``````
def find_unique_weight(students):
# 声明一个统计集合
unique_set = set()
# 循环所有学生数据
for id, weight in students:
# 集合会自动过滤重复数据
# 计算集合长度
ret = len(unique_set)
return ret``````

``````import time
id = [x for x in range(1, 10000)]
# 体重数据为了计算，也只能从 1 到 10000 了
weight = [x for x in range(1, 10000)]
students = list(zip(id, weight))

start_time = time.perf_counter()
# 调用列表计算函数
find_unique_weight(students)
end_time = time.perf_counter()
print("运算时间为：{}".format(end_time - start_time))``````