首页 > 代码库 > python dict

python dict

###字典的基本结构
info = {
    "k1" : "v1",
    "k2" : "v2"
}

 

###字典的valus可以是任何值
info = {
    "k1": 18,
    "k2": True,
    "k3": [
        11,
        [],
        (),
        22,
        33,
        {
            ‘kk1‘: ‘vv1‘,
            ‘kk2‘: ‘vv2‘,
            ‘kk3‘: (11,22),
        }
    ],
    "k4": (11,22,33,44)
}

 

###列表,字典不能作为字典的key
info = {
    #["a"]:3    

}

 

###字典是无序的
info = {
    "k1": 18,
    "k2": True,
    "k3": [
        11,
        [],
        (),
        22,
        33,
        {
            ‘kk1‘: ‘vv1‘,
            ‘kk2‘: ‘vv2‘,
            ‘kk3‘: (11,22),
        }
    ],
    "k4": (11,22,33,44)
}
print(info)
print(info)
print(info)

 

###索引方式找到指定的元素
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
print(info["k3"][5]["kk3"][0])       #===>11

 

###字典支持 del 删除
info = {
    "k1": 18,
    "k2": True,
    "k3": [
        11,
        [],
        (),
        22,
        33,
        {
            ‘kk1‘: ‘vv1‘,
            ‘kk2‘: ‘vv2‘,
            ‘kk3‘: (11,22),
        }
    ],
    "k4": (11,22,33,44)
}
del info["k3"][5]       #===>{‘k2‘: True, ‘k4‘: (11, 22, 33, 44), ‘k1‘: 18, ‘k3‘: [11, [], (), 22, 33]}
print(info)

 

###字典 for 循环
info = {
    "k1": 18,
    "k2": True,
    "k3": [
        11,
        [],
        (),
        22,
        33,
        {
            ‘kk1‘: ‘vv1‘,
            ‘kk2‘: ‘vv2‘,
            ‘kk3‘: (11,22),
        }
    ],
    "k4": (11,22,33,44)
}

#默认遍历key
for i in info:
    print(i)

#遍历values
for i in info.values():
    print(i)

#遍历key和values
for k,v in info.items():
    print(k,v)

 

#字典常用方法 get/update/keys/values/items
#根据Key获取值,key不存在时,可以指定默认值(None)
info = {
    "k1" : "v1",
    "k2" : "v2"
}
v = info.get("k1",)
vv = info.get("k111", 222)
print(v,vv)       #===>v1 222
print(info)       #===>{‘k2‘: ‘v2‘, ‘k1‘: ‘v1‘}

 

#更新
info = {
    "k1" : "v1",
    "k2" : "v2"
}
info.update({"k1":23131, "k3":"v3"})
print(info)        #===>{‘k3‘: ‘v3‘, ‘k2‘: ‘v2‘, ‘k1‘: 23131}

 

python dict