# 字典的定义方式: dict = {key01: value01, key02: value02, ...}
dict01 = {"Jerry": 63, "Tom": 72, "Hale": 85}
# 获取字典的长度.
print(len(dict01))
# 往字典中添加元素(键值对儿)
# add the element in the dict.
dict01["Role"] = 94
print(dict01)
dict01.setdefault("harry", 100)
print(dict01)
# 删除字典中的元素
# delete the element in the dict.
del dict01["Tom"]
print(dict01)
dict01.pop("harry", 100)
print(dict01)
# 修改字典中的元素值
# modify the element in the dict.
dict01["Role"] = 100
print(dict01)
dict01.update({"harry":94})
dict02 = {"Jerry": 120, "Hale": 58}
dict01.update(dict02)
print(dict01)
# 获取字典中所有的键或值
# seek the element in the dict.
print(dict01.get("Jerry"))
print(dict01.keys())
print(dict01.values())
# 遍历字典中的所有键值对,使用for循环
# traversing all element in the dict, using cycle(for).
for i in dict01.items():
print(i, type(i))
# 遍历字典中所有的key键使用for
# traversing all keys in the dict, using cycle(for).
for keys in dict01:
print(keys)
# 遍历字典中所有的值values
# traversing all values in the dict, using cycle(for).
for keys in dict01:
print("%s: %d" % (keys, dict01[keys]))
# 字典生成器
# dictionary generation.
list01 = ["Jerry", "Tom", "Hale", "Harry", "Role"]
dict03 = {}.fromkeys(list01)
print(dict03)
dict04 = {keys: None for keys in list01}
print(dict04)
dict05 = {keys: 0 for keys in range(11) if keys % 3 != 0}
print(dict05)
集合
# 定义集合
# set definition many style.
set01 = {1, 2, 3, 4, 5}
print(set01)
list01 = [1, 2, 3, 4, 5]
set02 = set(list01)
print(set02)
# 往集合中添加元素
# Add the element in the set.
set01.add(6)
print(set01)
list02 = [11, 22, 33, 44, 55]
set01.update(list02)
print(set01)
# 删除集合中的元素
# delete the element in the set.
set01.remove(11)
print(set01)
set01.pop()
print(set01)
set01.discard(77) # no error prompt.
print(set01)
# 遍历集合
# traversing all element in the set.
# for i in range(len(set01)):
# print(set01[i])
# TypeError: 'set' object does not support indexing.
# 集合生成器
# set generation.
set03 = {x for x in range(10) if x % 2 == 0}
print(set03)