python初学者指南:元祖与字典

简介: python初学者指南:元祖与字典

1 元祖


元祖中存储不能修改的数据。


1.1 元祖定义

元组特点:定义元组使用小括号,且逗号隔开各个数据,数据可以是不同的数据类型。


# 多个数据元组
t1 = (10, 20, 30)
# 单个数据元组
t2 = (10,)


注意:如果定义的元组只有一个数据,那么这个数据后面也好添加逗号,否则数据类型为唯一的这个数据的数据类型```


t2 = (10,)
print(type(t2))  # tuple
t3 = (20)
print(type(t3))  # int
t4 = ('hello')
print(type(t4))  # str


1.2 常见操作

1 按下标查找

tuple=('a','b')
print(tuple[0])  #a


2 index()

查找某个数据,如果数据存在返回对应的下标,否则报错,语法和列表、字符串的index方法相同。


3 count()

统计某个数据在当前元组出现的次数。


4 len()

统计元组中数据的个数。


2 字典


字典中的数据是以“键值对”的形式出现,字典中的数据没有顺序,所以也不支持下标,可以通过键的名字来查找数据。


2.1 字典定义

# 有数据字典
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
# 空字典
dict2 = {}
dict3 = dict()


特点:


  • 符号:{}
  • 键值对key:value形式出现,以逗号隔开


2.2 常见操作

1 增、改

字典为可变类型,所以可以对值进行修改,如果可以不存在则新增此键值对。


dict1['id'] = 110
# {'name': 'Rose', 'age': 20, 'gender': '男', 'id': 110}
print(dict1)
dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
dict1['name'] = 'Rose'
# 结果:{'name': 'Rose', 'age': 20, 'gender': '男'}
print(dict1)


2 删

del() / del


删除字典或删除字典中指定键值对。


dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
del dict1['gender']
# 结果:{'name': 'Tom', 'age': 20}
print(dict1)


clear()


清空字典


dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
dict1.clear()
print(dict1)  #{}


3 查

dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
print(dict1['name'])  # Tom
print(dict1['id'])  # `


如果当前查找的key存在,则返回对应的值;否则则报错。


get()

字典序列.get(key, 默认值)


注意:如果当前查找的key不存在则返回第二个参数(默认值),如果省略第二个参数,则返回None。


dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
print(dict1.get('name'))  # Tom
print(dict1.get('id', 110))  # 110默认值
print(dict1.get('id'))  # None


keys()


dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
print(dict1.keys())  # dict_keys(['name', 'age', 'gender'])
```


values


dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
print(dict1.items())  # dict_items([('name', 'Tom'), ('age', 20), ('gender', '男')])


3 遍历字典的键值对


dict1 = {'name': 'Tom', 'age': 20, 'gender': '男'}
for key, value in dict1.items():
    print(f'{key} = {value}')


image.png

image.png

目录
相关文章
|
6天前
|
Python
【Python操作基础】——字典,迭代器和生成器
【Python操作基础】——字典,迭代器和生成器
|
1天前
|
开发工具 Python
Python列表和字典前面为什么要加星号( )?_python一个 代表列表
Python列表和字典前面为什么要加星号( )?_python一个 代表列表
|
3天前
|
存储 索引 Python
【python学习】列表、元组、字典、集合,秋招是不是得到处面试
【python学习】列表、元组、字典、集合,秋招是不是得到处面试
|
6天前
|
索引 Python
Python中的列表、元组和字典各具特色
【5月更文挑战第11天】Python中的列表、元组和字典各具特色:列表是可变的,元组不可变,字典亦可变;列表和元组有序,字典无序(但在Python 3.7+保持插入顺序);元素类型上,列表和元组元素任意,字典需键不可变;列表用方括号[],元组用圆括号(),字典用大括号{}表示。列表不适合作字典键,元组可以。选择数据结构应依据实际需求。
23 2
|
6天前
|
开发者 Python
【Python 基础】递推式构造字典(dictionary comprehension)
【5月更文挑战第8天】【Python 基础】递推式构造字典(dictionary comprehension)
|
6天前
|
Python
Python中字典和集合(二)
Python中字典和集合(二)
|
6天前
|
存储 算法 索引
Python中字典和集合(一)
Python中字典和集合(一)
|
6天前
|
存储 缓存 Python
【Python21天学习挑战赛】字典 && 小数据池
【Python21天学习挑战赛】字典 && 小数据池
|
6天前
|
存储 JSON 数据处理
|
6天前
|
存储 缓存 人工智能
bidict,一个超酷的 Python 双向字典库!
bidict,一个超酷的 Python 双向字典库!
20 1