字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中
dic = {'name': 'zhangsan'}
print(type(dic))
print(dic)
print(str(dic))
# 返回指定键的值,如果值不在字典中返回default值
print(dic.get('age', 'no value'))
# 新增一个键
dic['age'] = 15
print(dic['age'])
# 以列表返回一个字典所有的键
print(dic.keys())
# 以列表返回字典中的所有值
print(dic.values())
# 复制
dic['chd'] = dic.copy()
print(dic)
# 循环输出键值对
for x, y in dic.items():
if type(y) == dict:
print(f'-- key: {x} child start--')
for a, b in y.items():
print(f'key:{a} , value:{b}')
print(f'-- key: {x} child end--')
else:
print(f'key:{x} , value:{y}')
# 删除
del dic['chd']
print(dic)
infos = [
{'name': 'zs', 'age': 18},
{'name': 'zs', 'age': 18},
{'name': 'zs', 'age': 18}
]
for index,item in enumerate(infos,xx):#xx设置多少index就从多少开始
print(f'id:{index} name:{item["name"]},age:{item["age"]}')
list1=['name','age','sex']
list2=['dog',18,'male']
zipobj=zip(list1,list2)
print(list(zipobj))
#[('name', 'dog'), ('age', 18), ('sex', 'male')]
x=dict(name='dog',age=18,sex='male')
print(x)
#{'name': 'dog', 'age': 18, 'sex': 'male'}
dic={'name':'zs','age':18,'city':'hz'}
print(dic.items()) #dict_items([('name', 'zs'), ('age', 18), ('city', 'hz')])
print(dic) #{'name': 'zs', 'age': 18, 'city': 'hz'}
print(dic.popitem()) #('city', 'hz')
print(dic) #{'name': 'zs', 'age': 18}
print(dic.pop('name','no')) #zs
print(dic) #{'age': 18}
d = {i: i for i in range(0,10,2)}
print(d)
#{0: 0, 2: 2, 4: 4, 6: 6, 8: 8}
lst1=['name','age','city']
lst2=['zs',18,'hz']
d={key:value for key,value in zip(lst1,lst2)}
print(d)
#{'name': 'zs', 'age': 18, 'city': 'hz'}
students = [
{'name': 'zhangsan', 'age': 18, 'city': 'hz'},
{'name': 'lisi', 'age': 19, 'city': 'sh'},
{'name': 'ww', 'age': 17, 'city': 'bj'}
]
for x in range(len(students)):
print('学生%(name)s的年龄是%(age)d,住在%(city)s' % students[x])
# 学生zhangsan的年龄是18,住在hz
# 学生lisi的年龄是19,住在sh
# 学生ww的年龄是17,住在bj
students = {'name': 'zhangsan', 'age': 18, 'city': 'hz'}
updateStudent={'name': 'zhangsan', 'age': 19, 'city': 'bj'}
students.update(updateStudent)
print(students)
#{'name': 'zhangsan', 'age': 19, 'city': 'bj'}

评论