【Python】Day 3

字典基础操作

#创建字典

1
2
3
4
5
6
dictionary = {
    "one":"name1",
    "two":"name2",
    "three":"name3"
}
print(dictionary)

#增加

1
2
dictionary["four"]="name4"
print(dictionary)

#修改

1
2
3
dictionary["one"]="name11"
print(dictionary)
#删除
1
2
3
4
5
6
7
8
del dictionary['two']
print(dictionary)
 
dictionary.pop("three")
print(dictionary)
 
dictionary.popitem()#随机删除
print(dictionary)

#查找

1
2
3
print('one' in dictionary)
print(dictionary.get('123'))#获取值
print(dictionary["one"])#相比get,如果不存在key,会报错,而get会返回none值

#多级字典嵌套及操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
dictionary_catalog={
    '娱乐':{
        1:'梦幻西游',
        2:'阴阳师',
        3:'剑灵'
    },
    '视屏':{
        1:'优酷网',
        2:['土豆网','可以看动漫'],
        3:'youtube'
    },
    '小说':{
        1:'斗破苍穹',
        2:'武动乾坤',
    }
}
print(dictionary_catalog)
dictionary_catalog['视屏'][2][1]='可以看电视剧'
print(dictionary_catalog)

#循环

1
2
3
4
5
for key in dictionary:
    print(key,dictionary[key])#优先使用此方法!
 
for k,v in dictionary.items():
    print(k,v)

About the Author

发表评论

电子邮件地址不会被公开。