python基础数据类型之字典+集合

Posted zgzeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python基础数据类型之字典+集合相关的知识,希望对你有一定的参考价值。

一、数据类型之字典

字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的。可哈希表示key必须是不可变类型,如:数字、字符串、元组。

字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

总结:1.字典是可变无序,且键唯一的数据类型,2.keys的数据类型不能是可变的数据类型,如列表和字典;

1.字典的创建

1.1 创建方法1:

dict1 = {"name": "zgzeng", "age": 23, "password": "xxx"}
print(type(dict1))    # <class ‘dict‘>

1.2 创建方法2:

dict2 = dict((("name", "zgzeng"),))
print(type(dict2))   # <class ‘dict‘>

2.字典的常用操作

2.1 字典增操作

2.1.1 dict[keys]

这种方法,当原字典中有这个key,那么就查询,当没有的时候,就为增操作

name = dict1["name"]
print(name)      # zgzeng
dict1["height"] = 183
print(dict1)
dict1 = {name: zgzeng, age: 23, password: xxx, height: 183}

2.1.2 setdefault

如果键存在,那么返回字典中原本的值,如果没有,那么增加,setdefault方法既可以作为曾操作,也可以作为查询操作
"""
Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.
"""
# 如果键存在,那么返回字典中原本的值,如果没有,那么增加
return1 = dict1.setdefault("age")
print(return1)  # 23
print(dict1)    # {‘name‘: ‘zgzeng‘, ‘age‘: 23, ‘password‘: ‘xxx‘, ‘height‘: 183}
return2 = dict1.setdefault("age", 18)
print(return2)  # 23
print(dict1)    # {‘name‘: ‘zgzeng‘, ‘age‘: 23, ‘password‘: ‘xxx‘, ‘height‘: 183}
return3 = dict1.setdefault("weight", "55kg")
print(return3)   # 55kg
print(dict1)     # {‘name‘: ‘zgzeng‘, ‘age‘: 23, ‘password‘: ‘xxx‘, ‘height‘: 183, ‘weight‘: ‘55kg‘}

2.2 字典查询操作

2.2.1 查询字典中所有的键

# 查询所有的键
print(dict1.keys())    # dict_keys([‘name‘, ‘age‘, ‘password‘, ‘height‘, ‘weight‘])
print(type(dict1.keys()))  # <class ‘dict_keys‘>
print(list(dict1.keys()))  # [‘name‘, ‘age‘, ‘password‘, ‘height‘, ‘weight‘]

2.2.2 查询字典中所有的值

# 查询所有的值
print(dict1.values())     # dict_values([‘zgzeng‘, 23, ‘xxx‘, 183, ‘55kg‘])
print(type(dict1.values()))   # <class ‘dict_values‘>

2.2.3 查询字典中的键和值

# 查询所有的值和键
print(dict1.items())   # dict_items([(‘name‘, ‘zgzeng‘), (‘age‘, 23), (‘password‘, ‘xxx‘), (‘height‘, 183), (‘weight‘, ‘55kg‘)])
print(type(dict1.items()))  # <class ‘dict_items‘>
print(list(dict1.items()))  # [(‘name‘, ‘zgzeng‘), (‘age‘, 23), (‘password‘, ‘xxx‘), (‘height‘, 183), (‘weight‘, ‘55kg‘)]

2.2.4 通过键来查值 + setdefault

 

2.3 字典操作改

类似列表的改操作

print(dict1)  # {‘name‘: ‘zgzeng‘, ‘age‘: 23, ‘password‘: ‘xxx‘, ‘height‘: 183, ‘weight‘: ‘55kg‘}
dict1["age"] = 24
print(dict1)  # {‘name‘: ‘zgzeng‘, ‘age‘: 24, ‘password‘: ‘xxx‘, ‘height‘: 183, ‘weight‘: ‘55kg‘}

通过update修改

类似与列表的批量追加,将字典2添加到字典1中,如果有重复的key,那么字典2中的覆盖字典1中的,如果没有则添加

"""
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
"""

dict2 = {"name": "zgzeng", "age": 25, "hobby": "code", "drink": "tea"}
dict1 = {name: zgzeng, age: 24, password: xxx, height: 183, weight: 55kg}
dict1.update(dict2)
print(dict1)   # {‘name‘: ‘zgzeng‘, ‘age‘: 25, ‘password‘: ‘xxx‘, ‘height‘: 183, ‘weight‘: ‘55kg‘, ‘hobby‘: ‘code‘, ‘drink‘: ‘tea‘}

 

2.4 字典操作删除

2.4.1  指定删除del方法

del dict[key]


print(dict1)   # {‘name‘: ‘zgzeng‘, ‘age‘: 25, ‘password‘: ‘xxx‘, ‘height‘: 183, ‘weight‘: ‘55kg‘, ‘hobby‘: ‘code‘, ‘drink‘: ‘tea‘}
del dict1["height"]
print(dict1)  # {‘name‘: ‘zgzeng‘, ‘age‘: 25, ‘password‘: ‘xxx‘, ‘weight‘: ‘55kg‘, ‘hobby‘: ‘code‘, ‘drink‘: ‘tea‘}

 2.4.2 pop删除 

指定删除,并返回该删除的键值对的值

print(dict1)  # {‘name‘: ‘zgzeng‘, ‘age‘: 25, ‘password‘: ‘xxx‘, ‘weight‘: ‘55kg‘, ‘hobby‘: ‘code‘, ‘drink‘: ‘tea‘}
# 返回删除值
a = dict1.pop("age")
print(a)   # 25
print(dict1)  #{‘name‘: ‘zgzeng‘, ‘password‘: ‘xxx‘, ‘weight‘: ‘55kg‘, ‘hobby‘: ‘code‘, ‘drink‘: ‘tea‘}

2.4.3 popitem随机删除

字典是无序的

b = dict1.popitem()
print(b)  # (‘drink‘, ‘tea‘)
print(dict1)  # {‘name‘: ‘zgzeng‘, ‘password‘: ‘xxx‘, ‘weight‘: ‘55kg‘, ‘hobby‘: ‘code‘}

2.4.4 清空clear


print(dict1)  # {‘name‘: ‘zgzeng‘, ‘password‘: ‘xxx‘, ‘weight‘: ‘55kg‘, ‘hobby‘: ‘code‘}
dict1.clear()
print(dict1)   # {}

2.4.5 删除整个字典del

内存中没有这个字典了

print(dict1)   # {}
del dict1
print(dict1)   # NameError: name ‘dict1‘ is not defined

 

2.4.6 其他操作和方法

fromkeys

# fromkeys
""" Returns a new dict with keys from iterable and values equal to value. """
D = {}
L = [1, 2, 3]
print(D.fromkeys(L))      # {1: None, 2: None, 3: None}
print(D.fromkeys(L, "password"))    # {1: ‘password‘, 2: ‘password‘, 3: ‘password‘}

len

# len
D = {
    "k1": "v1",
    "k2": "v2",
    "k3": "v3",
}
print(len(D))    # 3

字典的嵌套

info = {
    "China": {
        "zgzeng": {"age": 23, "height": 183, "job": "IT", "hobby": ["sport", "music", "coding"]}
    }
}

# 如果过了一年,zgzeng又长大了一岁,我们修改他的年纪,并且不喜欢运动喜欢上了打游戏
info["China"]["zgzeng"]["age"] = 24
info["China"]["zgzeng"]["hobby"][0] = "play game"
print(info)
# {‘China‘: {‘zgzeng‘: {‘age‘: 24, ‘height‘: 183, ‘job‘: ‘IT‘, ‘hobby‘: [‘play game‘, ‘music‘, ‘coding‘]}}}

排序sort

列表的排序是通过内容来排序,字母通过asc码表来排序,字典是根据key来排序

字典通过sorted函数来排序

dict3 = {"k1": "v1", "k2": "v2", "k3": "v3"}
print(sorted(dict3.values()))  # [‘v1‘, ‘v2‘, ‘v3‘]
print(sorted(dict3))    # [‘k1‘, ‘k2‘, ‘k3‘]
print(sorted(dict3.items()))  # [(‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘), (‘k3‘, ‘v3‘)]

 

字典的遍历

 

for i in dict3:
    print(i, dict3[i])

"""
k1 v1
k2 v2
k3 v3
"""

for i in dict3.items():
    print(i)
"""
(‘k1‘, ‘v1‘)
(‘k2‘, ‘v2‘)
(‘k3‘, ‘v3‘)
"""
这两种方法推荐使用第一种来遍历键值对,因为第二种效氯不高

遍历值
for i in dict3.values():
print(i)
”“”

v1
v2
v3


““”


 

 二、集合

一个包含唯一元素的可变和无序的集合数据类型

 1.集合的创建

# 集合
# 集合的创建1se = {1., 2, False, (), {}, [], " "}print(type(se))     # TypeError: unhashable type: ‘dict‘se = {1, 2, False, (), [], " "}print(type(se))       # TypeError: unhashable type: ‘list‘

se = {1, 2, False, (), " "}
print("se的数据类型是:", type(se))     # se的数据类型是: <class ‘set‘>

se2 = {}
print("se2的数据类型是:", type(se2))    # se2的数据类型是: <class ‘dict‘>
# 注意,当se2中的数据为空的时候,它是一个空字典,并非一个空集合
# 集合的创建2
se3 = set()
print("se3的数据类型是:", type(se3))     # se3的数据类型是: <class ‘set‘>

 

2.集合(set)的方法

2.1 增

"""
set() -> new empty set object
set(iterable) -> new set object
Build an unordered collection of unique elements.
"""
se.add("hello world!")
print(se)    # {‘‘, 1, ‘hello world!‘, ()}


""" Update a set with the union of itself and others. """
se.update("hello")
print(se)    # {‘‘, 1, ‘o‘, ‘hello world!‘, (), ‘l‘, ‘e‘, ‘h‘}  集合是无序的且是唯一的
se.update(("hello", "hello world"))
print(se)    # {‘‘, 1, ‘o‘, ‘hello‘, ‘hello world!‘, ‘h‘, ‘e‘, ‘l‘, (), ‘hello world‘}

# 两种增加的方法,update将增加的元素拆分,添加到集合中

2.2 删(pop/remove/discard)

pop 

"""
Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
"""

se = {1., 2, "hello world!", ()}
a = se.pop()
print(a)      # 1.0
print(se)     # {2, (), ‘hello world!‘}
se = set()
se.pop()
print(se) # KeyError: ‘pop from an empty set‘
# 随机删除,有则删除且有返回值,如果集合中没有元素,那么报错

remove

# 指定删除remove和discard
# remove
"""
        Remove an element from a set; it must be a member.

        If the element is not a member, raise a KeyError.
"""

se = {1., 2, "hello world!", ()}
se.remove(())
print(se)      # {1.0, 2, ‘hello world!‘}

se.remove("hello")
print(se)    #     se.remove("hello")  KeyError: ‘hello‘

"""
        Remove an element from a set if it is a member.

        If the element is not a member, do nothing.
"""
se.discard(2)
print(se)    # {1.0, ‘hello world!‘}
se.discard("hello")
print(se)    # {1.0, ‘hello world!‘}

# 两种删除方法都是指定删除,不同之处就是当集合中没有需要指定删除的元素的时候,remove方法就会报错,而discard方法不做任何操作

3. 交集、并集、差集

# 交集(&)
se1 = {1, 3, 47, 18, 90, 100}
se2 = {1, 3, 90, 47, "hello world!"}
se3 = se1 & se2
print(se3)     # {1, 90, 3, 47}


# 并集(|)
se1 = {1, 3, 47, 18, 90, 100}
se2 = {1, 3, 90, 47, "hello world!"}
se3 = se1 | se2
print(se3)    # {1, 3, 100, ‘hello world!‘, 47, 18, 90}


# 差集(-)
se1 = {1, 3, 47, 18, 90, 100}
se2 = {1, 3, 90, 47, "hello world!"}
s3 = se1 - se2
print(s3)    # {18, 100}
s4 = se2 - se1
print(s4)   # {‘hello world!‘}

# 相对差集(^)  
se1 = {1, 3, 47, 18, 90, 100}
se2 = {1, 3, 90, 47, "hello world!"}
s6 = se1 ^ se2
print(s6) # {18, 100, ‘hello world!‘}

4. 集合的应用

# 列表去重
li = [1, 3, "hello world!", 4, 9, "hello world!", 45, 2, 1, 5, 9]
li3 = list(set(li))
print(li3)    # [1, 2, 3, 4, 5, 9, 45, ‘hello world!‘]

 

 

 



以上是关于python基础数据类型之字典+集合的主要内容,如果未能解决你的问题,请参考以下文章

python基础之数据类型的比较

python基础数据类型之字典dict和集合set及其他(for,enumerate,range)。

Python 基础之集合及基本数据类型总结

Python基础之集合

[Python系列-5]:Python之人工智能 - 基本语法-2- 类复合数据类型容器(列表集合元组字典)

python基础之列表,字典,集合