您的位置:首页 > 编程语言 > Python开发

Python学习打卡--day25(基础练习:字典和元组)

2019-05-24 22:57 597 查看
# 字典和元组的创建
d1 = {'name': 'jason', 'age': 20, 'gender': 'male'}
print(d1)
d2 = dict({'name': 'jason', 'age': 20, 'gender': 'male'})
print(d2)
d3 = dict([('name', 'jason'), ('age', 20), ('gender', 'male')])
print(d3)
d4 = dict(name='jason', age=20, gender='male')
print(d4)
s = {1, 'hello', 5.0}
print(s)
s1 = {1, 2, 3}
print(s1)
s2 = set([1, 2, 3])
print(s2)

# 元素的访问
d = {'name': 'jason', 'age': 20}
print(d['name'])
# print(d['name1'])  key不存在会报错
print(d.get('name'))
print(d.get('name22'), 'null')

ss = {1, 2, 3}
# print(ss[0]) # 集合不支持索引操作

# 判断一个元素在不在字典/集合内,可以用 value in dict/set 来判断
print('name' in d)
print('json' in d)
print(1 in ss)
print(5 in ss)

# 增加/删除/更新操作
dd = {'name': 'jason', 'age': 20}
dd['gender'] = 'male'  # 增加元素对
print(dd)
dd['gender'] = 'female'
print(dd)
dd.pop('age')  # 删除元素对
print(dd)

sss = {1, 12, 3, 4, 88, 9}
sss.add(6)  # 增加元素
print(sss)
sss.remove(3)  # 删除元素
print(sss)
sss.pop()  # 删除最后一个元素,但集合本身是无序的;慎用
print(sss)

# 排序操作
d_1 = {'b': 1, 'a': 2, 'c': 10}
print(d_1.items())  # 返回由字典项 ((键, 值) 对) 组成的一个新视图
d_sort_by_key = sorted(d_1.items(), key=lambda x: x[0])  # 根据字典键的升序排序
print(d_sort_by_key)
d_sorted_by_value = sorted(d_1.items(), key=lambda x: x[1])  # 根据字典值的升序排序
print(d_sorted_by_value)

s_1 = {3, 5, 1, 2}
print(sorted(s_1))  # 升序,返回一个新列表
print(sorted(s_1, reverse=True))  # 降序,返回一个新列表
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: