字典与集合

字典dict

字典是python数据结构中最为重要的。常用的名字有哈希表、关联数组;
主要的特点为:键值对集合,其中键key和值value都是python对象;
(1)键是不可变的对象,值可以是任意的
(2)字典是一个无序的集合,序列由于没有key做对应,因此以顺序/索引来对应值,序列有序而字典无序

字典的创建

可以使用如下几种方式来创建字典
(1)使用{}花括号创建字典

mapping = {}
keylst = ['a', 'b', 'c']
valuelst = [1,2,3]

for key, value in zip(keylst, valuelst):
    mapping[key] = value
mapping
------------------------------------
{'a': 1, 'b': 2, 'c': 3}

(2)使用序列生成字典

keylst = ['a', 'b', 'c']
valuelst = [1,2,3]
dict(zip(keylst, valuelst)) 
-----------------------------------
{'a': 1, 'b': 2, 'c': 3}

zip函数我们在后续章节会做介绍

(3)使用dict.fromkeys(lst)方法

keylst = ['a', 'b', 'c']
dict.fromkeys(keylst)
dict.fromkeys(keylst, 'today')
-----------------------
{'a': None, 'b': None, 'c': None}
{'a': 'today', 'b': 'today', 'c': 'today'}

字典的增删改查

(1)增:直接给键赋予对应的值即可

mapping = {}
mapping['color'] = 'black'
print(mapping)
------------------------------
{'color': 'black'}

(2)删

  • 使用语句del dict[key]
  • 使用方法dict.pop(key)
dic = {'a': 'white', 'b': 'black', 'c': 'red'}
print(dic)
dic.pop('a')
print(dic)
del dic['c']
print(dic)
---------------------------------------
{'a': 'white', 'b': 'black', 'c': 'red'}
{'b': 'black', 'c': 'red'}
{'b': 'black'}

(3)改:直接根据key来修改其对应的值

dic = {'a': 'white', 'b': 'black', 'c': 'red'}
print(dic)
dic['a'] = 'yellow'
print(dic)
---------------------------
{'a': 'white', 'b': 'black', 'c': 'red'}
{'a': 'yellow', 'b': 'black', 'c': 'red'}

(4)查

  • dic[key]
  • key in dic: 成员判断,只能使用key去做判断,不能使用value
dic = {'a': 'white', 'b': 'black', 'c': 'red'}
print(dic['c'])
print('a' in dic)
print('c' in dic.keys())
-------------------------
red
True
True

字典常用方法

(1)dict.keys()
生成一个视图,通常使用list(dict.keys())返回字典所有的键,以列表的形式展现

dic = {'a': 'white', 'b': 'black', 'c': 'red'}
print(dic.keys(), type(dic.keys()))
print(list(dic.keys()))
----------------------------------
dict_keys(['a', 'b', 'c']) 
['a', 'b', 'c']

(2)dict.values()
生成一个视图,可以使用list进行转换,list(dict.values()),返回字典所有的值
(3)dic.items():输出字典的所有元素,原理同上述两种方法,注意如下例子非常重要,后续字典与列表的转换通常会采用类型的结构来处理。

dic = {'a': 'white', 'b': 'black', 'c': 'red', 'name': 'Alice', 'age': 22, 'city': 'Shanghai'}
print(list(dic.items()))
------------------------------------------
[('a', 'white'), ('b', 'black'), ('c', 'red'), ('name', 'Alice'), ('age', 22), ('city', 'Shanghai')]

(4)dict1.update(dict2)
合并两个字典,更改dict1,而不会改变dict2,如果dict1与dict2中有相同的键,那么合并后的键对应的值会被覆盖掉,与此同时最后的输出是无序的

dic1 = {'a': 'white', 'b': 'black', 'c': 'red'}
dic2 = {'name': 'Alice', 'age': 22, 'city': 'Shanghai'}
dic1.update(dic2)
print(dic1)
---------------------------------
{'a': 'white', 'b': 'black', 'c': 'red', 'name': 'Alice', 'age': 22, 'city': 'Shanghai'}

(5)dict.get(key)
直接查看key对应的value值,如果没有相应的key则返回None,添加print参数可以多返回一个值,dic.get(key, print("nothing")),表示如果没有对应的key,则输出nothing

dic = {'a': 'white', 'b': 'black', 'c': 'red', 'name': 'Alice', 'age': 22, 'city': 'Shanghai'}
print(dic.get('city'))
print(dic.get('addr', print('nothing')))
-------------------------------------
Shanghai
nothing
None

字典的键的属性

从字典的定义中我们知道,字典是无序的,且键是不可变的对象,值可以是任意的python对象。

  • 不可变对象:标量类型,元组,字符串,注意列表不是不可变对象
    那么有没有办法能快速识别一个对象是否可以作为字典的键呢??
  • hash函数的使用
hash((1,2,3))
hash('hello')
hash([1,2]):报错,因为列表不可以作为字典的键,除非先将列表转换成元组
print(hash((1,2,3)))
print(hash('hello'))
-----------------------
2528502973977326415
803241608788734770
hash([1,2,3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in 
----> 1 hash([1,2,3])

TypeError: unhashable type: 'list'

字典元素的访问与遍历

for keys in dict:
for key in dict.keys():
for v in dic.values():
for (k, v) in dic.items():
scores = [('语文', 98), ('数学', 120), ('英语', 100)]
dic = dict(scores)

for key in dic:
    print(key)

for value in dic.values():
    print(value)
    
for (k, v) in dic.items():
    print(k, v)
------------------------
语文
数学
英语
98
120
100
语文 98
数学 120
英语 100

集合

集合是一种无序且元素唯一/不重复的容器,可以认为集合类似于字典,但是没有键

创建集合

创建集合可以使用如下两种方法:
(1)通过set函数:set(list)
(2)直接使用花括号:{1,2,3,4,5}

lst = [2, 4, 8, 4, 2, 4, 5]
print(set(lst), type(set(lst)))
set1 = {1, 3, 4, 1, 5}
print(set1)
------------------------
{8, 2, 4, 5} 
{1, 3, 4, 5}

集合的方法

(1)增

a.add(x)

set1 = {1, 2, 3, 4, 5, 9}
set1.add(10)
print(set1) 
>>> {1, 2, 3, 4, 5, 9, 10}

(2)删

a.clear():删除整个集合
a.remove(x):删除集合中x这个元素
a.pop():随机删除一个值
set1 = {1, 2, 3, 4, 5, 9}
set1.clear()
print(set1)  >>> set()
set1 = {1, 2, 3, 4, 5, 9}
set1.remove(5)
print(set1) 
>>> {1, 2, 3, 4, 9}
set1 = {8, 2, 3, 4, 5, 9}
set1.pop()
print(set1)
>>>
{3, 4, 5, 8, 9}

集合的运算

假设有两个集合:a = {1,2,3} b = {1, 77,88}

  • a.union(b):a和b中所有不同的元素 a | b
  • a.update(b):将a集合设置为a和b的并集 a |= b
  • a.intersection(b):两个集合的交集 a & b
  • a.difference(b):在a中不在b中的元素 a - b
  • a.issubset(b):如果a包含于b,则返回True
  • a.issuperset(b):如果a包含b返回True
  • a.isdisjoint(b):a,b没有交集返回True

重点注意:

集合中的元素必须是不可变的,这与字典是类似的,因此如果想要包含列表型元素,必须先转换成元组

你可能感兴趣的:(字典与集合)