python学习之字典

Posted 凉生墨客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习之字典相关的知识,希望对你有一定的参考价值。

字典是另一种可变容器模型,且可存储任意类型对象。字典的每个键值(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}

 

以上是关于python学习之字典的主要内容,如果未能解决你的问题,请参考以下文章

python学习之字典

python学习之字典的操作

python3学习之字典

Python学习之字典

python学习之字典

python学习之数据类型—字典dict