【Python学习记录】字典

(1)定义:

stu ={
    "name": "zxc",
    "school": "hqu"
}

(2)访问:

print(stu["name"])
print(stu["school"])

结果:

zxc
hqu

(3)添加键-值

stu ={
    "name": "zxc",
    "school": "hqu"
}

stu["age"] = 19

(4)修改键-值

stu ={
    "name": "zxc",
    "school": "hqu"
}

stu["name"]="cj"

(5)删除键-值

del stu["name"]

(6)遍历字典

  (6.1)遍历键-值 items()   返回一个键-值列表

stu ={
    "name": "zxc",
    "school": "hqu"
}

for key,value in stu.items():
    print(key+":"+value)

结果:

name:zxc
school:hqu

  (6.2)遍历所有的键 key()    返回一个键列表

stu ={
    "name": "zxc",
    "school": "hqu"
}

for key in stu.keys():
    print(key)

结果:

name
school

  (6.3)遍历所有的值 values()       返回一个值列表

stu ={
    "name": "zxc",
    "school": "hqu"
}

for value in stu.values():
    print(value)

结果:

zxc
hqu

(7)字典列表 

  (7.1)定义

定义:列表中包含着很多字典。

zxc = {
    "name": "zxc",
    "school": "hqu"
}

lzh = {
    "name": "lzh",
    "school": "police"
}

stu = [zxc, lzh]

  (7.2)在字典列表中添加

方法:append()

zxc = {
    "name": "zxc",
    "school": "hqu"
}

lzh = {
    "name": "lzh",
    "school": "police"
}

stu =[zxc,lzh]

yyb = {
    "name": "yyb",
    "school": "xmu"
}

stu.append(yyb)

(8)在字典中存储列表

    (8.1)定义

stu = {
    "name":"zxc",
    "school":["tkk","hqu","xmu"]
}

(8.2)访问列表

stu = {
    "name":"zxc",
    "school":["tkk","hqu","xmu"]
}

school = stu["school"]
print(school)

(9)字典中的字典

stu = {
    "zxc":{
            "school": "hqu",
            "target": "xmu"
    },

    "zlh":{
        "name": "lzh",
        "information": {
            "school": "police",
            "target": "zz"
        }
    }

}

访问:

stu = {
    "zxc":{
            "school": "hqu",
            "target": "xmu"
    },

    "zlh":{
        "name": "lzh",
        "information": {
            "school": "police",
            "target": "zz"
        }
    }

}

zxc = stu["zxc"]
for key,value in zxc.items():
    print(key+":"+value)

结果:

school:hqu
target:xmu

 

你可能感兴趣的:(python)