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 ^ se2print(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!‘]


原文地址:https://www.cnblogs.com/zgzeng/p/12041248.html

时间: 2024-08-05 18:08:14

python基础数据类型之字典+集合的相关文章

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

2.6字典dict. 2.6.1 字典的初识 1. 列表可以存储大量的数据类型,但是如果数据量大的话,他的查询速度比较慢. 2. 列表只能按照顺序存储,数据与数据之间关联性不强. 所以针对于上的缺点,说咱们需要引入另一种容器型的数据类型,解决上面的问题,这就需要dict字典. 数据类型可以按照多种角度进行分类,就跟咱们人一样,人按照地域可以划分分为亚洲人,欧洲人,美洲人等,但是按照肤色又可以分为白种人,黄种人,黑种人,等等,数据类型可以按照不同的角度进行分类,先给大家按照可变与不可变的数据类型的

python基础数据类型一(字典)

字典 列表可以存储大量的数据类型,但是只能按照顺序存储,数据与数据之间关联性不强. 所以咱们需要引入一种容器型的数据类型,解决上面的问题,这就需要dict字典. 字典(dict)是python中唯?的?个映射类型.他是以{ }括起来的键值对组成. 在dict中key是 唯?的.在保存的时候, 根据key来计算出?个内存地址. 然后将key-value保存在这个地址中. 这种算法被称为hash算法, 所以, 切记, 在dict中存储的key-value中的key必须是可hash的 可以改变的都是不

python基础 filter ,列表,字典,集合 中根据 条件 筛选 数据

from random import randint data = [randint(-10, 10) for _ in xrange(10)] print data e = filter(lambda x: x >= 0, data) print e 或者使用  列表解析       速度快 [x for x in data if x >= 0] 对字典的筛选 d = {x: randint(60, 100) for x in xrange(1, 21)} print d print {k:

python基础数据类型之set(集合)

set(集合)   set中的数据是唯一的,set中的数据可以改变 创建set li=set({"hello","nice"})     //如果创建一个空的,只能li=set() li={"hello","nice"} m=["hello","nice"] li=set(m)  //通过一个可迭代来创建set 2.set的一些方法     a.difference(b)  //a和b都

2 Python基础数据类型

Python基础数据类型 # 数据类型分为可变数据类型和不可变数据类型 # 可变数据类型:list.set.dict 不可哈希 # 不可变数据类型:str.int.bool.tuple(元祖) 可哈希 基本类型和数据集 基本类型 int 数字型:int 1,2,3,56 取值范围为:-2\*\*31~2**31-1 可以进行的运算:+ - * / **(幂次方) %(取余) type() 查看数据类型 str 字符串:str python中只要是用引号引起来的全是字符串 字符串转化成数字的条件:

python基础数据类型----整数 ,字符串【常用操作方法】,布尔值,for循环

Python基础数据类型(4.29) bool str int 三者之间的转换 str索引切片,常用操作方法 for循环(大量的练习题) 1.基础数类型总览 整数(int) ,字符串(str),布尔值(bool),列表(list),元组(tuple),字典(dict),集合(set). 10203 123 3340 int 主要用于计算+- * / 等等 '今天吃了没?' str 存储少量的数据,并进行相应的操作.str1 + str2, str *int , 索引,切片, 其他操作方法 Tru

python基础数据类型补充以及编码的进阶

一. 基础数据类型补充内容 1.1 字符串 字符串咱们之前已经讲了一些非常重要的方法,剩下还有一些方法虽然不是那么重要,但是也算是比较常用,在此给大家在补充一些,需要大家尽量记住. #captalize :首字母大写 #swapcase :大小写翻转 #title :每个单词的首字母大写 #center :内同居中,总长度,空白处填充 #寻找字符串中的元素是否存在 #find :返回的找到的元素的索引,如果找不到返回-1 #index :返回的找到的元素的索引,找不到报错. #captalize

Py西游攻关之基础数据类型(四)-字典

Py西游攻关之基础数据类型 - Yuan先生 https://www.cnblogs.com/yuanchenqi/articles/5782764.html 七 Dictionary(字典) 字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据.python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的.可哈希表示key必须是不可变类型,如:数字.字符串.元组. 字典(dictionary)是除列表意

Python基础数据类型考试题

# Python基础数据类型考试题 # 考试时间:两个半小时 满分100分(80分以上包含80分及格) # 一,基础题. # 1, 简述变量命名规范(3分) # 1.变量由字母.数字.下划线任意组成 # 2.不能以数字开头 # 3.不能使用python关键字 # 4.变量要具有可描述性 # 5.变量不能是中文 # 5.官网推荐骆峰体和下划线,这里推荐下划线 # 2,字节和位的关系.(2分) # 1字节 = 8位 # 3,'太白'使用utf-8编码时,占的位数和字节数,是多少?使用gbk编码时,占