字典相关的函数
字典操作(字典里的键必须是唯一)
dict_1 ={'name':'shenzhen','age':'40','score':'90' } print (dict_1)
1.往字典中添加键值对
dict["key"] = "value"
dic_1={"fruit":"orange","food":"meat","foods":"orange"} dic_1["city"]="shenzhen" print(dic_1)
setdefault()如果键不已经存在于字典中,将会添加键并将值设为默认值。
dic_1={"fruit":"orange","food":"meat","foods":"orange"} dic_1.setdefault("name") print(dic_1) #结果{'fruit': 'orange', 'food': 'meat', 'foods': 'orange', 'name': None}
dic_1={"fruit":"orange","food":"meat","foods":"orange"} dic_1.setdefault("name","shenzhen") print(dic_1) #结果{'fruit': 'orange', 'food': 'meat', 'foods': 'orange', 'name': 'shenzhen'}
2.替换字典中指定键的值 dict["key"] = "value"
dic_1={"fruit":"orange","food":"meat","foods":"orange"} dic_1["fruit"]="apple" print(dic_1)
3.update()一个字典所有项追加到另一个字典里
dic_1={"fruit":"orange","food":"meat","foods":"orange"} dic_2={"country":"china"} dic_1.update(dic_2) print(dic_1) print("新字典:",dic_1) print(dic_2)
4.字典取值 get()函数返回指定键的值,如果值不在字典中返回默认值。
dic_1={"fruit":"orange","food":"meat","foods":"orange"} print(dic_1.get("fruit")) print(dic_1.get("name"))#键不存在返回值为None print("键返回的值是:%s" % dic_1.get("food"))
dic_1={"fruit":"orange","food":"meat","foods":"orange","zhongguo":{"guangdong":"shenzhen","guangxi":"nanning"}} print(dic_1.get("zhongguo"))
5.keys()从字典中取出所有键,可通过 list() 来转换为列表
dic_1={"fruit":"orange","food":"meat","foods":"orange","zhongguo":{"guangdong":"shenzhen","guangxi":"nanning"}} dic_2=dic_1.keys() print(dic_2) print(type(dic_2))
#通过list()方法转换为列表
print(list(dic_2))
6.values() 从字典中取出所有值,可以使用 list() 来转换为列表,列表为字典中的所有值
dic_1={"fruit":"orange","food":"meat","foods":"orange","zhongguo":"guangdong"} dic_2=dic_1.values() print(dic_2)
#通过list()方法转换为列表
list_1=list(dic_2)
print(list_1[3])
7.del 删除键值对
dic_1={"fruit":"orange","food":"meat","foods":"orange","zhongguo":"guangdong"} del dic_1["fruit"] #删除对应的键值对 print(dic_1)
#可以通过del 删除整个字典
del dic_1
8.pop()删除字典给定键 key 所对应的值,返回值为被删除的值。
dic_1={"fruit":"orange","food":"meat","foods":"orange","zhongguo":"guangdong"} print(dic_1.pop("fruit"))#返回值为"orange" print(dic_1)
9.popitem()随机删除字典的键值对
dic_1={"fruit":"orange","food":"meat","foods":"orange","zhongguo":"guangdong"} new_1=dic_1.popitem() print(type(new_1))#返回值为包含被删除的键值对的一个元组 print(new_1) print(dic_1)
10.clear()函数用于删除字典内所有元素,没有返回值。
dic_1={"fruit":"orange","food":"meat","foods":"orange","zhongguo":"guangdong"} dic_1.clear() print(dic_1)
11.copy()复制创建字典
dic_1={"fruit":"orange","food":"meat","foods":"orange","zhongguo":"guangdong"} new_dic=dic_1.copy() print("复制的新字典为:",new_dic)
12.in或not in检查字典是否有指定的键,有结果为 True,没有结果为 False
dic_1={"fruit":"orange","food":"meat","fruits":"orange","zhongguo":"guangdong"} print("fruit" in dic_1) print("foods" not in dic_1)