Python基础语法7 —— 字典(Dictionary)

目录

字典实例、字典的访问、字典的修改、字典的删除、字典的成员检测、字典的内置函数


Python 字典(Dictionary)

字典是另一种可变容器模型,且可存储任意类型对象。



字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:

d = {key1 : value1, key2 : value2 }

键必须是唯一的,但值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
一个简单的字典实例:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
dict = { 'abc': 123, 98.6: 37 };

访问字典里的值

d = {"one":1,"two":2,"three":3}
#注意访问格式,中括号内是键值
print(d["one"]) #1

d["one"] = "eins"
print(d)
#{'one': 'eins', 'two': 2, 'three': 3}

修改字典
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
#dict['Age']:  8
#dict['School']:  DPS School

删除使用del操作

d = {"one":1,"two":2,"three":3}
del d["one"]
print(d)
#{'two': 2, 'three': 3}

成员检测 in,not in 检测key内容

d = {"one":1,"two":2,"three":3}

if 2 in d:
    print("value")

if "two" in d:
    print("key")

if ("two",2) in d:
    print("kv")

#key



字典内置函数

Python字典包含了以下内置函数:

序号 函数 描述
1 cmp(dict1, dict2) 比较两个字典元素。
2 len(dict) 计算字典元素个数,即键的总数。
3 str(dict) 输出字典可打印的字符串表示。
4 type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。

猜你喜欢

转载自blog.csdn.net/dyw_666666/article/details/81069466