Python基础: 数据类型二

字典

# 字典的定义方式: 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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

好好学技术oH

你的鼓励是一起学习的动力何阶梯

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值