Python_字典
Posted liutianyuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python_字典相关的知识,希望对你有一定的参考价值。
字典的魔法
1、字典dict 的定义以大括号里的冒号为分割的一个个键值对组成
dic = { "k1": ‘v1‘, #键值对 "k2": ‘v2‘ }
2、字典的value可以是任何值
info = { "k1": 18, "k2": True, "k3": [ 11, [], (), 22, 33, { ‘kk1‘: ‘vv1‘, ‘kk2‘: ‘vv2‘, ‘kk3‘: (11,22), } ], "k4": (11,22,33,44) } print(info)
3、字典是无序的
4、字典可以通过索引取得元素
info = { "k1": 18, 2: True, "k3": [ 11, [], (), 22, 33, { ‘kk1‘: ‘vv1‘, ‘kk2‘: ‘vv2‘, ‘kk3‘: (11,22), } ], "k4": (11,22,33,44) } # v = info[‘k1‘] # print(v) # v = info[2] # print(v) v = info[‘k3‘][5][‘kk3‘][0] print(v)
5、字典支持del进行删除
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)
6、字典支持for循环,但是for循环时它默认循环的只有key
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.values(): # 输出key所对应的values print(item) for k,v in info.items(): # 即输出key又输出value print(k,v)
以上是关于Python_字典的主要内容,如果未能解决你的问题,请参考以下文章