Python 字典数据类型

1、字典的定义

person = {"name":"小明","age":18}

2、字典操作

查找

示例代码如下:

person = {"name":"小明","age":18}
print(person["name"]) # 小明

添加

示例代码如下:

person = {"name":"小明","age":18}
person["height"] = 170
print(person) # {'name': '小明', 'age': 18, 'height': 170}

更改

示例代码如下:

person = {"name":"小明","age":18}
person[“name”] = “小红”
print(person) # {'name': '小红', 'age': 18}

删除

示例代码如下:

person = {"name":"小明","age":18}
person.pop("age")
print(person) # {'name': '小红'}

3、字典的遍历

遍历所有key

示例代码如下:

person = {"name":"小明","age":18}
for k in person:
	print(k) # name age

遍历所有value

示例代码如下:

person = {"name":"小明","age":18}
for v in person.values():
	print(v) # 小明 18

同时遍历key,value

示例代码如下:

person = {"name":"小明","age":18}
for k,v in person.items():
	print(k,v) # name 小明 age 18
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页