python学习之字典
字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,字典属于dict类,格式如下所示:
1、基本机构
info = { "k1": "v1", # 键值对 "k2": "v2" # 键值对 }
2、字典的value可以是任何值
#!/usr/bin/env python info = { "k1": 18, "k2": True, "k3": [ 11, [], (), 22, 33, { 'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11,22), } ], "k4": (11,22,33,44) } print(info)
结果:
{'k1': 18, 'k2': True, 'k3': [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}], 'k4': (11, 22, 33, 44)}
3、列表、字典不能作为字典的key
#!/usr/bin/env python info ={ 1: 'asdf', "k1": 'asdf', True: "123", # [11,22]: 123 (11,22): 123, # {'k1':'v1'}: 123 } print(info)
结果:
{1: '123', 'k1': 'asdf', (11, 22): 123}
4、索引方式找到指定元素
#!/usr/bin/env python info = { "k1": 18, 2: True, "k3": [ 11, [], (), 22, 33, { 'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11,22), } ], "k4": (11,22,33,44) } v = info['k3'][5]['kk3'][0] print(v)
结果:
11
5、字典支持 del 删除
#!/usr/bin/env python info = { "k1": 18, 2: True, "k3": [ 11, [], (), 22, 33, { 'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11,22), } ], "k4": (11,22,33,44) } del info['k1'] del info['k3'][5]['kk1'] print(info)
结果:
{2: True, 'k3': [11, [], (), 22, 33, {'kk2': 'vv2', 'kk3': (11, 22)}], 'k4': (11, 22, 33, 44)}
6、支持for循环
#!/usr/bin/env python info = { "k1": 18, 2: True, "k3": [ 11, [], (), 22, 33, { 'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11,22), } ], "k4": (11,22,33,44) } for item in info: print(item) for item in info.keys(): print(item) for item in info.values(): print(item) for item in info.keys(): print(item,info[item]) for k,v in info.items(): print(k,v) info ={ "k1": 'asdf', True: "123", # [11,22]: 123 (11,22): 123, # {'k1':' v1'}: 123 } print(info)
结果:
k1 2 k3 k4 k1 2 k3 k4 18 True [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}] (11, 22, 33, 44) k1 18 2 True k3 [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}] k4 (11, 22, 33, 44) k1 18 2 True k3 [11, [], (), 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22)}] k4 (11, 22, 33, 44) {'k1': 'asdf', True: '123', (11, 22): 123}
7、get方法
根据key去取值,如果没有key则返回None,也可以用来表示当要取的key不存在时,用默认的值返回。
dic ={
"name":'wang',
"age":23
}
v = dic.get('name')
v1=dic.get('age1')
v2=dic.get('age1',100)
print(v,v1,v2)
结果:
wang None 100
8、pop方法,删除指定的key
dic ={ "name":'wang', "age":23 } dic.pop('name') print(dic) 结果: {'age': 23}
9、setdefault
如果key已经存在,不设置值,获取当前key对应的值
如果key不存在,设置值,获取当前key对应的值
dic ={ "name":'wang', "age":23 } v=dic.setdefault('name',"zhang") print(dic,v) dic1 ={ "name":'wang', "age":23 } v1=dic1.setdefault('name1',"zhang") print(dic1,v1) 结果: {'name': 'wang', 'age': 23} wang {'name': 'wang', 'name1': 'zhang', 'age': 23} zhang
10、keys、values方法
dic ={ "name":'wang', "age":23 } v=dic.keys() v1=dic.values() print(v,v1) 结果: dict_keys(['name', 'age']) dict_values(['wang', 23])
作者:凉生墨客
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。