十一、初识python-dict(课时26)

字典的创建

  • 字典是序列类型,但是无序,不可索引和切片
  • 每个数据都由键值对组成,即kv对
    • key:可哈希的值,比如str、int、float,但list、tuple、dict不行
    • value:任何值
# 空字典创建1
k = {}
print(k)

# 空字典创建2
d = dict()
print(d)

# 有内容字典创建,每一组数据用冒号隔开,每一对键值用逗号隔开
d = {"one":555, "two":666, "three":777}
print(d)

# 用dict创建有内容字典1
d = dict({"one":555, "two":666, "three":777})

# 用dict创建有内容字典2,用关键字参数的方法创建
d = dict(one=555, two=666, three=777)
print(d)

# unknow
d = dict([("one",555),("two",666),("three",777)])
print(d)
'''
{}
{}
{'one': 555, 'two': 666, 'three': 777}
{'one': 555, 'two': 666, 'three': 777}
{'one': 555, 'two': 666, 'three': 777}
'''

字典的常见操作

# 访问数据
d = {"one":555, "two":666, "three":777}
# 访问的是键值
print(d["one"])

#赋值
d["one"] = 111
print(d)

#删除
del d["one"]
print(d)
'''
555
{'one': 111, 'two': 666, 'three': 777}
{'two': 666, 'three': 777}
'''

# 成员检测,检测的是key内容
d = {"one":555, "two":666, "three":777}

if "one" in d:
    print("key")
    
if 555 in d:
    print("value")
    
if ("one",555) in d:
        print("k,v")
#结果为key

字典的遍历

d = {"one":555, "two":666, "three":777}

# 按key使用for循环
for k in d:
    print(k, d[k])
    
# 上述可改写为
# 更清楚地标名访问的是键值
for k in d.keys():
    print(k, d[k])
    
# 只访问字典的值
for v in d .values():
    print(v)
    
# 特殊用法
for k,v in d.items():
    print(k, "---", v)
    
print("*" * 50)

for k in d:
    print(k)
'''
one 555
two 666
three 777
one 555
two 666
three 777
555
666
777
one --- 555
two --- 666
three --- 777
**************************************************
one
two
three
'''

字典的生成

d = {"one":555, "two":666, "three":777}

dd = {k:v for k,v in d.items()}
print(dd)

ddd = {k:v for k,v in d.items() if v % 2 == 0}
print(ddd)
'''
{'one': 555, 'two': 666, 'three': 777}
{'two': 666}
'''

字典的相关函数

# len,max,min,clear与其他的使用方法相同
d = {"one":555, "two":666, "three":777}

#str(字典),返回字典的字符串格式
d1 = str(d)
print(d1)
print(type(d1))

#items(),返回字典的元组格式
d2 = d.items()
print(d2)
print(type(d2))

#keys(),返回字典的键组成的一个结构
d3 = d.keys()
print(d3)
print(type(d3))

#values(),同理,返回一个可迭代的结构
d4 = d.values()
print(d4)
print(type(d4))
'''
{'one': 555, 'two': 666, 'three': 777}
<class 'str'>

dict_items([('one', 555), ('two', 666), ('three', 777)])
<class 'dict_items'>

dict_keys(['one', 'two', 'three'])
<class 'dict_keys'>

dict_values([555, 666, 777])
<class 'dict_values'>
'''

# get,根据指定键访问一个相应的值,好处是可以返回一个默认值,不会报错,默认值是None
d = {"one":555, "two":666, "three":777}
print(d.get("one33"))
print(d.get("one33",100))
print(d["one33"])
'''
None
100
KeyError
'''

# fromkeys:使用指定的序列作为键,使用一个值作为字典所有键的值
l = ["one", "two", "three"]
d = dict.fromkeys(l, "这就是一个值")
print(d)
#{'one': '这就是一个值', 'two': '这就是一个值', 'three': '这就是一个值'}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值