标签:image 技术 values ict 默认值 get key 符号 键值
# 1. 有数据的字典
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
print(dict1)
# 2. 创建空字典
dict2 = {}
print(type(dict2)) # <class ‘dict‘>
dict3 = dict()
print(type(dict3)) # <class ‘dict‘>
注意:如果key存在则修改这个key对应的值,如果key不存在则新增此键值对
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
# key存在,修改值
dict1[‘name‘] = ‘Rose‘
print(dict1) # {‘name‘: ‘Rose‘, ‘age‘: 20, ‘gender‘: ‘male‘}
# key不存在,新增
dict1[‘id‘] = 110
print(dict1) # {‘name‘: ‘Rose‘, ‘age‘: 20, ‘gender‘: ‘male‘, ‘id‘: 110}
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
# 1.del 删除字典或指定的键值对
# 删除字典
# del dict1
# print(dict1) # NameError: name ‘dict1‘ is not defined
# 删除指定的键值对
del dict1[‘name‘]
print(dict1) # {‘age‘: 20, ‘gender‘: ‘male‘}
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
# clear() 清空字典
dict1.clear()
print(dict1) # {}
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
# key存在,修改值
dict1[‘name‘] = ‘Rose‘
print(dict1) # {‘name‘: ‘Rose‘, ‘age‘: 20, ‘gender‘: ‘male‘}
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
# 1.[key]
print(dict1[‘name‘]) # key存在,返回对应的值
# print(dict1[‘names‘]) # key不存在,报错
如果当前查找的key存在,则返回对应的值;否则报错
dict.get(key,default)
注意:如果当前查找的key不存在则返回第二个参数(默认值),如果省略第二个参数,则返回None
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
# get()
print(dict1.get(‘name‘)) # Tom
print(dict1.get(‘id‘)) # None
print(dict1.get(‘id‘, 110)) # 110
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
# keys() 查找字典中所有的key,返回可迭代对象
print(dict1.keys()) # dict_keys([‘name‘, ‘age‘, ‘gender‘])
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
# values() 查找字典中所有的values,返回可迭代对象
print(dict1.values()) # dict_values([‘Tom‘, 20, ‘male‘])
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
# items() 查找字典中所有的键值对,返回可迭代对象,里面的数据是元组,元组数据1是字典的key,元组数据2是字典的values
print(dict1.items()) # dict_items([(‘name‘, ‘Tom‘), (‘age‘, 20), (‘gender‘, ‘male‘)])
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
for key in dict1.keys():
print(key)
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
for value in dict1.values():
print(value)
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
for item in dict1.items():
print(item)
dict1 = {‘name‘: ‘Tom‘, ‘age‘: 20, ‘gender‘: ‘male‘}
for key,value in dict1.items():
print(f‘{key} = {value}‘)
标签:image 技术 values ict 默认值 get key 符号 键值
原文地址:https://www.cnblogs.com/qian-yuan/p/14604732.html