标签:模型 指定元素 结果 索引 print 存储 span pre for
字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:
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、布尔值(1,0)、列表、字典不能作为字典的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}
标签:模型 指定元素 结果 索引 print 存储 span pre for
原文地址:https://www.cnblogs.com/heruiguo/p/9122817.html