# 字典的创建# 创建空字典
d ={}print(d)print(type(d))
d =dict()print(d)# 创建有值的字典,每一组数据用冒号隔开,每一对键值对用逗号隔开
d ={"one":1,"two":2,"three":3}print(d)# 用dict创建有内容字典1
d =dict({"one":1,"two":2,"three":3})print(d)# 用dict创建有内容字典2# 利用关键字参数
d =dict(one=1,two=2,three=3)print(d)#
d =dict([("one",1),("two",2),("three",3)])
# 成员检测, in , not in# 成员检测检测的是key的内容
d ={"one":1,"two":2,"three":3}if2in d:print("value")if"two"in d:print("key")if("two",2)in d:print("kv")
key
# 遍历在python2和3中区别较大,代码不通用# 按 key来使用for循环
d ={"one":1,"two":2,"three":3}# 使用for循环,直接按key值访问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)
one 1
two 2
three 3
one 1
two 2
three 3
1
2
3
one -- 1
two -- 2
three -- 3
字典生成式
#常规字典生成式
d ={"one":1,"two":2,"three":3}
dd ={k:v for k,v in d.items()}print(dd)#加限制条件字典生成式
d ={"one":1,"two":2,"three":3}
dd ={k:v for k,v in d.items()if v %2==0}print(dd)
{'one': 1, 'two': 2, 'three': 3}
{'two': 2}
字典相关函数
# 通用函数:len ,max , min ,dict# str(字典): 返回字典的字符串格式
d ={"one":1,"two":2,"three":3}print(str(d))
{'one': 1, 'two': 2, 'three': 3}
# clear: 清空字典# items: 返回字典的键值对组成的元祖格式
d ={"one":1,"two":2,"three":3}
i = d.items()print(type(i))print(i)