柚子的Python学习笔记之字典

字典:Python中字典是一种key-value的数据类型,就像新华字典那样,可以根据笔划,字母来查找对应的内容。

定义语法:

dict = {
    'num1101':"Alice",
    'num1102':"Alen",
    'num1103':"Alex",
    'num1104':"BOb",
    'num1105':"Linda",
}

字典的特性:

  • 无序
  • key必须唯一,所以字典天生去重,不存在重复元素

字典操作

增加

dict = {
    'num1101':"Alice",
    'num1102':"Alen",
    'num1103':"Alex",
    'num1104':"BOb",
    'num1105':"Linda",
}
print(dict)
dict["num1106"] = "June这里是新元素"
print(dict)

柚子的Python学习笔记之字典_第1张图片

删除

dict.pop("num1101")  #标准删除方法
del dict["num1102"]  #删除指定元素
dict.popitem()       #删除最后一个元素
print(dict)

柚子的Python学习笔记之字典_第2张图片

修改

dict['num1101'] = "爱丽丝"

查找

dict = {
    'num1101':"Alice",
    'num1102':"Alen",
    'num1103':"Alex",
    'num1104':"BOb",
    'num1105':"Linda",
}
print("num1103" in dict)        #返回检索的元素是否存在,Trur,false
print(dict.get("num1105"))      #返回对应的值
print(dict["num1104"])          #如检索值不存在会报错
print(dict["num1109"])

#输出如下:
True
Traceback (most recent call last):
Linda
  File "/home/cc/mycode/day3/dict.py", line 11, in 
BOb
    print(dict["num1109"])
KeyError: 'num1109'

Process finished with exit code 1

多级字典嵌套

多级字典嵌套即在字典中定义字典;

book = {
    "学习工具":{
        "1001":["百科全书"],
        "1002": ["英汉互译"],
        "1003": ["Python入门"],
    },
    "小说":{
        "1101":["解忧杂货店"],
        "1102": ["好吗好的"],
        "1103": ["百年孤独"],
    },
    "名著":{
        "1201":["西游记","红楼梦"],
    }
}
book["学习工具"]["1003"][0] += ",学习Python的好帮手"
print(book["学习工具"]["1003"]) 

柚子的Python学习笔记之字典_第3张图片

其他操作

values
dict = {
    'num1101':"Alice",
    'num1102':"Alen",
    'num1103':"Alex",
    'num1104':"BOb",
    'num1105':"Linda",
}

print(dict.values())
输出:dict_values(['Alice', 'Alen', 'Alex', 'BOb', 'Linda'])
keys
dict = {
    'num1101':"Alice",
    'num1102':"Alen",
    'num1103':"Alex",
    'num1104':"BOb",
    'num1105':"Linda",
}
print(dict.keys())

输出:dict_keys(['num1101', 'num1102', 'num1103', 'num1104', 'num1105'])

setdefault
dict = {
    'num1101':"Alice",
    'num1102':"Alen",
    'num1103':"Alex",
    'num1104':"BOb",
    'num1105':"Linda",
}

dict.setdefault("num1106","Jane")            #检索后不存在该元素,添加进字典
dict.setdefault("num1101","爱丽丝")           #检索后存在该元素,字典内容不变
print(dict)

输出应为:{‘num1101’: ‘Alice’, ‘num1102’: ‘Alen’, ‘num1103’: ‘Alex’, ‘num1104’: ‘BOb’, ‘num1105’: ‘Linda’, ‘num1106’: ‘Jane’}

update
dict = {
    'num1101':"Alice",
    'num1102':"Alen",
    'num1103':"Alex",
    'num1104':"BOb",
    'num1105':"Linda",
}

name = {
    1:2,"num1105":"Linda",3:4
}

dict.update(name)
print(dict)
{'num1101': 'Alice', 'num1102': 'Alen', 'num1103': 'Alex', 'num1104': 'BOb', 'num1105': 'Linda', 1: 2, 3: 4}
items
循环

你可能感兴趣的:(Python,学习,Python字典)