ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

【Python】Dict模块

2020-12-03 12:32:48  阅读:145  来源: 互联网

标签:dict1 模块 Python two Dict key print 字典


Dict 特征
通过键而不是通过索引来读取元素 字典类型有时也称为关联数组或者散列表(hash)。它是通过键将一系列的值联系起来的,这样就可以通过键从字典中获取指定项,但不能通过索引来获取。
字典是任意数据类型的无序集合 和列表、元组不同,通常会将索引值 0 对应的元素称为第一个元素,而字典中的元素是无序的。
字典是可变的,并且可以任意嵌套 字典可以在原处增长或者缩短(无需生成一个副本),并且它支持任意深度的嵌套,即字典存储的值也可以是列表或其它的字典。
字典中的键必须唯一 字典中,不支持同一个键出现多次,否则只会保留最后一个键值对。
字典中的键必须不可变 字典中每个键值对的键是不可变的,只能使用数字、字符串或者元组,不能使用列表。

 

 

 

 

 

 

 

 

 

 

 

使用 { } 创建字典

由于字典中每个元素都包含两部分,分别是键(key)和值(value),因此在创建字典时,键和值之间使用冒号:分隔,相邻元素之间使用逗号,分隔,所有元素放在大括号{ }中。

使用{ }创建字典的语法格式如下:

dictname = {'key':'value1', 'key2':'value2', ..., 'keyn':valuen}

其中 dictname 表示字典变量名,keyn : valuen 表示各个元素的键值对。需要注意的是,同一字典中的各个键必须唯一,不能重复。

如下代码示范了使用花括号语法创建字典:

#使用字符串作为key
scores = {'数学': 95, '英语': 92, '语文': 84}
print(scores)
#使用元组和数字作为key
dict1 = {(20, 30): 'great', 30: [1,2,3]}
print(dict1)
#创建空元组
dict2 = {}
print(dict2)

 

运行结果为:

{'数学': 95, '英语': 92, '语文': 84}
{(20, 30): 'great', 30: [1, 2, 3]}
{}

可以看到,字典的键可以是整数、字符串或者元组,只要符合唯一和不可变的特性就行;字典的值可以是 Python 支持的任意数据类型。

 

 

2) 通过 fromkeys() 方法创建字典

Python 中,还可以使用 dict 字典类型提供的 fromkeys() 方法创建带有默认值的字典,具体格式为:

dictname = dict.fromkeys(list,value=None)

其中,list 参数表示字典中所有键的列表(list);value 参数表示默认值,如果不写,则为空值 None。

请看下面的例子:

knowledge = ['语文', '数学', '英语']字典
scores = dict.fromkeys(knowledge, 60) print(scores)

dict5 = dict.fromkeys("abc", 'x')
print(dict5)

# {'a': 'x', 'b': 'x', 'c': 'x'}

_dict5 = dict.fromkeys({1, 2, 3})
print(_dict5)

# {1: None, 2: None, 3: None}

运行结果为:

{'语文': 60, '英语': 60, '数学': 60}

可以看到,knowledge 列表中的元素全部作为了 scores 字典的键,而各个键对应的值都是 60。这种创建方式通常用于初始化字典,设置 value 的默认值。

 

 

3) 通过 dict() 映射函数创建字典

通过 dict() 函数创建字典的写法有多种,表 2 罗列出了常用的几种方式,它们创建的都是同一个字典 a。

创建字典
a = dict(str1=value1, str2=value2, str3=value3) str 表示字符串类型的键,value 表示键对应的值。使用此方式创建字典时,字符串不能带引号。
#方式1
demo = [('two',2), ('one',1), ('three',3)]
#方式2
demo = [['two',2], ['one',1], ['three',3]]
#方式3
demo = (('two',2), ('one',1), ('three',3))
#方式4
demo = (['two',2], ['one',1], ['three',3])
a = dict(demo)
向 dict() 函数传入列表或元组,而它们中的元素又各自是包含 2 个元素的列表或元组,其中第一个元素作为键,第二个元素作为值。
keys = ['one', 'two', 'three'] #还可以是字符串或元组
values = [1, 2, 3] #还可以是字符串或元组
a = dict( zip(keys, values) )
通过应用 dict() 函数和 zip() 函数,可将前两个列表转换为对应的字典。

3) 通过推导创建字典

dict6 = {i: 2 * i for i in range(3)}
print(dict6)  # {0: 0, 1: 2, 2: 4}

注意,无论采用以上哪种方式创建字典,字典中各元素的键都只能是字符串、元组或数字,不能是列表。列表是可变的,不能作为键。

 

4) 创建键值一对多的字典

一般写法: 使用Python3标准库,collections模块的类:defaultdict([default_factory[, …]])

  • 需要导入collections模块的defaultdict
  • 接受一个工厂函数作为参数,default_factory可以是list,tuple,set等
  • defaultdict会根据method_factory参数不同为key设置默认值,而相同情况下普通Dict会抛出KeyError
from collections import defaultdict

dict2 = defaultdict(list)
dict2["one"].append(1)
dict2["one"].append(2)
dict2["one"].append(3)
print(dict2)  # defaultdict(<class 'list'>, {'one': [1, 2, 3]})
print(dict2["two"])  # key"two"不存在 根据参数是list返回空列表 []

 

6) 创建有序字典

创建有序Dict
推荐写法: 使用Python3的标准库,collections模块的类:OrderedDict([items])

    • OrderedDict内部维护着一个根据键插入顺序排序的双向链表,每添加一个新元素,它会被放到链表尾部
    • 缺点:相比于普通Dict,OrderedDict会造成更多内存消耗
dict1 = OrderedDict()
dict1["one"] = 1
dict1["two"] = 2
dict1["three"] = 3
print(dict1)  # OrderedDict([('one', 1), ('two', 2), ('three', 3)])

 

7) 创建空字典

推荐写法: 使用{}直接创建

推荐写法: 使用Python3的标准库,dict类内置函数:dict()

empty_dict1 = {}
print(isinstance(empty_dict1, dict))  # True
print(empty_dict1)  # {}


empty_dict2 = dict()
print(isinstance(empty_dict2, dict))  # True
print(empty_dict2)  # {}

 

 

8) 创建有默认值的字典

推荐写法: 使用Python3的标准库,dict类内置函数:setdefault(key[, default]),key指定键,default是可选参数

  • default指定默认返回值
  • 若key已存在,则返回其对应的值,default不生效
  • 若key不存在,若给定default返回值,则返回该值,并把键值对(key, default)插入到当前字典中
  • 若key不存在,若没有给定default返回值,则返回None,并把键值对(key, None)插入到当前字典中
dict1 = {"one": 1, "two": 2, "three": 3}

value = dict1.setdefault("one", 111)
print(value)  # key"one"存在 default不生效 1
print(dict1)  # {'one': 1, 'two': 2, 'three': 3}

none_value = dict1.setdefault("four")
print(none_value)  # key"four"不存在 None
print(dict1)  # 添加新元素 {'one': 1, 'two': 2, 'three': 3, 'four': None}

default_value = dict1.setdefault("five", 5)
print(default_value)  # key"five"不存在 返回default给定值 5
print(dict1)  # 添加新元素 {'one': 1, 'two': 2, 'three': 3, 'four': None, 'five': 5}

 

 

 

 

 

Python访问字典

列表和元组是通过下标来访问元素的,而字典不同,它通过键来访问对应的值。因为字典中的元素是无序的,每个元素的位置都不固定,所以字典也不能像列表和元组那样,采用切片的方式一次性访问多个元素。

Python 访问字典元素的具体格式为:dictname[key]

其中,dictname 表示字典变量的名字,key 表示键名。注意,键必须是存在的,否则会抛出异常。

除了上面这种方式外,Python 更推荐使用 dict 类型提供的 get() 方法来获取指定键对应的值。当指定的键不存在时,get() 方法不会抛出异常。

get() 方法的语法格式为:dictname.get(key[,default])

其中,dictname 表示字典变量的名字;key 表示指定的键;default 用于指定要查询的键不存在时,此方法返回的默认值,如果不手动指定,会返回 None。

注意,当键不存在时,get() 返回空值 None,如果想明确地提示用户该键不存在,那么可以手动设置 get() 的第二个参数,例如:

a = dict(two=0.65, one=88, three=100, four=-59)
print( a.get('one') )
print( a.get('five', '该键不存在') )

 

Python删除字典

和删除列表、元组一样,手动删除字典也可以使用 del 关键字,例如:

a = dict(two=0.65, one=88, three=100, four=-59)
print(a)
del a
print(a)

 

Dict浅拷贝

Dict浅拷贝只会拷贝当前Dict的顶层元素,不会拷贝嵌套的子对象,即原Set和拷贝Set指向同一子对象
一般写法: 使用Python3的标准库,dict类内置函数:copy(other),other指代另一个Dict

    • 返回一个新Dict,与原Dict地址空间不同
    • 若当前Dict包含子对象,则不会拷贝子对象,原Dict和拷贝Dict指向同一子对象
    • 更新子对象会同时影响原Dict和拷贝Dict
dict1 = {"one": 1, "two": {1: 1, 2: 2}}

copy1 = dict1.copy()
print(dict1 == copy1)  # True
print(id(dict1) == id(copy1))  # False

copy1.get("two")[1] = 111
print(dict1)  # {'one': 1, 'two': {1: 111, 2: 2}}

一般写法: 使用Python3的标准库,copy模块的函数:copy(other),other指代另一个Dict

  • 需要导入copy模块
  • 返回一个新Dict,与原Dict地址空间不同
  • 若当前Dict包含子对象,则不会拷贝子对象,原Dict和拷贝Dict指向同一子对象
  • 更新子对象会同时影响原Dict和拷贝Dict
import copy

dict1 = {"one": 1, "two": {1: 1, 2: 2}}

copy1 = copy.copy(dict1)
print(dict1 == copy1)  # True
print(id(dict1) == id(copy1))  # False

copy1.get("two")[1] = 111
print(dict1)  # {'one': 1, 'two': {1: 111, 2: 2}}

一般写法: 使用Python3的标准库,dict类内置函数:dict(other),other指代另一个Dict

  • 返回一个新Dict,与原Dict地址空间不同
  • 若当前Dict包含子对象,则不会拷贝子对象,原Dict和拷贝Dict指向同一子对象
  • 更新子对象会同时影响原Dict和拷贝Dict
dict1 = {"one": 1, "two": {1: 1, 2: 2}}

copy1 = dict(dict1)
print(dict1 == copy1)  # True
print(id(dict1) == id(copy1))  # False

copy1.get("two")[1] = 111
print(dict1)  # {'one': 1, 'two': {1: 111, 2: 2}}

一般写法: 使用运算符”=“

  • 本质是对象的引用
  • 返回一个新Dict,与原Dict指向同一个地址空间,相互影响
dict1 = {"one": 1, "two": {1: 1, 2: 2}}

copy1 = dict1
print(dict1 == copy1)  # True
print(id(dict1) == id(copy1))  # True

copy1.get("two")[1] = 111
print(dict1)  # {'one': 1, 'two': {1: 111, 2: 2}}

 

 

Dict深拷贝

Dict深拷贝不仅会拷贝当前Dict的顶层元素,也会拷贝嵌套的子对象,本质上是执行递归浅拷贝,原Dict和拷贝Dict完全独立,相互不影响
推荐写法: 使用Python3的标准库,copy模块的函数:deepcopy(other),other指代另一个Dict

    • 需要导入copy模块
    • 返回一个新Dict,与原Dict是独立的对象,地址空间不同
    • 若当前Dict包含子对象,也会拷贝子对象
    • 原Dict和拷贝Dict所有元素地址都是独立的,更新元素相互不影响
import copy

dict1 = {"one": 1, "two": {1: 1, 2: 2}}

copy1 = copy.deepcopy(dict1)
print(dict1 == copy1)  # True
print(id(dict1) == id(copy1))  # False

copy1.get("two")[1] = 111
print(dict1)  # {'one': 1, 'two': {1: 1, 2: 2}}

获取Dict长度

获取字典长度
推荐写法: 使用Python3的标准库,内置函数len(s),参数可以是序列(如字符串、字节、元组、列表或范围等)或集合(如字典和集合),这里是Dict实例

dict1 = {"one": 1, "two": 2, "three": 3}

length = len(dict1)
print(length)  # 3

empty_dict = {}
empty_length = len(empty_dict)
print(empty_length)  # 0

 

Dict添加

Dict添加键值对

添加一个键值对

Dict添加单个元素;键必须是不可变对象,比如数字、字符串或元组(纯元组,没有嵌套可变对象),否则会抛出TypeError
推荐写法: 使用方括号dict1[key]=value直接赋值,指定键和值

    • 若key已存在,则会修改相应的值,若key不存在,则添加元素
    • 性能比update函数高
dict1 = {"one": 1, "two": 2, "three": 3}
dict1["four"] = 4
print(dict1) # {'one': 1, 'two': 2, 'three': 3, 'four': 4}
dict1["one"] = 111
print(dict1) # {'one': 111, 'two': 2, 'three': 3, 'four': 4}

一般写法: 使用Python3的标准库,dict类内置函数:update([other]),other指代一个字典对象或一个键值对的迭代

  • 若key已存在,则会修改相应的值,若key不存在,则添加元素
  • 性能比直接赋值低
dict1 = {"one": 1, "two": 2, "three": 3}

# 通过关键字形式的参数添加
dict1.update(four=4)
print(dict1)  # {'one': 1, 'two': 2, 'three': 3, 'four': 4}

# 通过元组列表参数添加
dict1.update([("five", 5)])
print(dict1)  # {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}

# 通过字典实例参数添加
dict1.update({"six": 6})
print(dict1)  # {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}

# 可以使用以上任意方法修改已存在的键对应的值
dict1.update(one=111)
print(dict1)  # {'one': 111, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}

 

添加多个键值对

Dict添加多个元素;键必须是不可变对象,比如数字、字符串或元组(纯元组,没有嵌套可变对象),否则会抛出TypeError
一般写法: 使用Python3的标准库,dict类内置函数:update([other]),other指代一个字典对象或一个键值对的迭代

    • 若key已存在,则会修改相应的值,若key不存在,则添加元素
dict1 = {1: 1, 2: 2, 3: 3}

# 通过关键字形式的参数添加
dict1.update(four=4, five=5)
print(dict1)  # {1: 1, 2: 2, 3: 3, 'four': 4, 'five': 5}

# 通过元组列表参数添加
dict1.update([(6, 6), (7, 7)])
print(dict1)  # {1: 1, 2: 2, 3: 3, 'four': 4, 'five': 5, 6: 6, 7: 7}

# 通过字典参数添加
dict1.update({8: 8, 9: 9})
print(dict1)  # {1: 1, 2: 2, 3: 3, 'four': 4, 'five': 5, 6: 6, 7: 7, 8: 8, 9: 9}

# 可以使用以上任意方法修改已存在的键对应的值
dict1.update({"four": 444, "five": 555})
print(dict1)  # {1: 1, 2: 2, 3: 3, 'four': 444, 'five': 555, 6: 6, 7: 7, 8: 8, 9: 9}

 

Dict删除

Dict删除键值对

1) 根据指定的key删除一个键值对

Dict根据指定的键删除一个键值对
推荐写法: 使用Python3的标准库,dict类内置函数:pop(key[, default]),key指定键,default是可选参数

    • default指定默认返回值
    • 若key已存在,则删除相应的键值对,并返回其对应的值,default不生效
    • 若key不存在,若给定default返回值,则返回该值,否则抛出KeyError
    • 参数不能为空
dict1 = {"one": 1, "two": 2, "three": 3}

value1 = dict1.pop("one", 111)
print(value1)  # key"one"存在 default不生效 1
print(dict1)  # {'two': 2, 'three': 3}

value2 = dict1.pop("1", 111)
print(value2)  # key"1"不存在 返回default给定值 111
print(dict1)  # {'two': 2, 'three': 3}

dict1.pop("1")  # key"1"不存在 抛出KeyError: '1'
dict1.pop()  # 抛出TypeError: pop expected at least 1 arguments, got 0

一般写法: 使用del关键字:del dict1[key],key指定键

  • 若key已存在,则删除相应的键值对
  • 若key不存在,则抛出KeyError
dict1 = {"one": 1, "two": 2, "three": 3}

del dict1["one"]
print(dict1)  # {'two': 2, 'three': 3}

del dict1["1"]  # key"1"不存在 抛出KeyError: '1'

2) 随机删除一个键值对

Dict随机删除一个键值对
推荐写法: 使用Python3的标准库,dict类内置函数:popitem()

    • 随机删除一个键值对,并以元组的形式返回该键值对
    • 若Dict为空,则抛出KeyError
dict1 = {"one": 1, "two": 2, "three": 3}

pop_one = dict1.popitem()
print(pop_one)  # ('three', 3)
print(dict1)  # {'one': 1, 'two': 2}

empty_dict = {}
empty_dict.popitem()  # 抛出KeyError: 'popitem(): dictionary is empty'

3) 清空Dict

删除Dict中所有元素
推荐写法: 使用Python3的标准库,dict类内置函数:clear()

    • 修改当前集合,删除Dict中所有元素
dict1 = {"one": 1, "two": 2, "three": 3}
dict1.clear()
print(dict1)  # {}

4) 删除整个Dict

删除整个字典变量
推荐写法: 使用关键字“del”

    • del作用于变量而不是对象
    • del只是解除变量和对象的引用关系,而不是销毁对象释放占用的内存空间
    • python的垃圾回收机制主要采用的是引用计数的方式
dict1 = {"one": 1, "two": 2, "three": 3}
del dict1
print(dict1)  # 抛出NameError: name 'dict1' is not defined

6. Dict更新

1) 更新指定key的value

Dict更新指定key对应的value
推荐写法: 使用方括号dict1[key]=value直接更新,指定键和值

    • 若key已存在,则会修改相应的值,若key不存在,则添加元素
    • 性能比update函数高
dict1 = {"one": 1, "two": 2, "three": 3}

dict1["one"] = 111
print(dict1)  # {'one': 111, 'two': 2, 'three': 3}

dict1["four"] = 4
print(dict1)  # {'one': 111, 'two': 2, 'three': 3, 'four': 4}

一般写法: 使用Python3的标准库,dict类内置函数:update([other]),other指代一个字典对象或一个键值对的迭代

  • 若key已存在,则会修改相应的值,若key不存在,则添加元素
  • 性能比直接赋值低
    dict1 = {"one": 1, "two": 2, "three": 3}
    
    # 通过关键字形式的参数更新
    dict1.update(one=111)
    print(dict1)  # {'one': 111, 'two': 2, 'three': 3}
    
    # 通过元组列表参数更新
    dict1.update([("two", 222)])
    print(dict1)  # {'one': 111, 'two': 222, 'three': 3}
    
    # 通过字典参数更新
    dict1.update({"three": 333})
    print(dict1)  # {'one': 111, 'two': 222, 'three': 333}
    
    # 可以使用以上任意方法添加一个键值对
    dict1.update(four=4)
    print(dict1)  # {'one': 111, 'two': 222, 'three': 333, 'four': 4}

     

7. Dict查找

1) 获取value的最大值/最小值

获取value的最大值/最小值
推荐写法: 使用Python3的标准库,内置函数:max/min(iterable, *[, key, default])和zip(*iterables)

    • 返回value的最大值/最小值及其对应的key构成的元组
dict1 = {"a": 123, "b": 321, "c": 200}

# 获取max value及其对应的key
max_tuple = max(zip(dict1.values(), dict1.keys()))
print(max_tuple)  # (321, 'b')

# 获取min value及其对应的key
min_tuple = min(zip(dict1.values(), dict1.keys()))
print(min_tuple)  # (123, 'a')

一般写法: 使用Python3的标准库,内置函数:max/min(iterable, *[, key, default])

  • 获取value的最大值/最小值对应的key,再根据key获取对应的value
dict1 = {"a": 123, "b": 321, "c": 200}

# 在一个字典上执行普通的数学运算,它们仅仅作用于键,而不是值
max_key = max(dict1)
print(max_key)  # 返回key的最大值 'c'

# 获取最大值对应的键
max_value_key = max(dict1, key=lambda k: dict1[k])
print(max_value_key)  # 'b'
 
# 根据键获取对应的值
max_value = dict1[max_key]
print(max_value)  # 321

2) 获取指定key的value

获取指定key的value
推荐写法: 使用Python3的标准库,dict类内置函数:get(key[, default]),key指定键,default是可选参数

    • default指定默认返回值
    • 若key已存在,则返回其对应的值,default不生效
    • 若key不存在,若给定default返回值,则返回该值,否则返回None
    • 所以该方法永远不会引发KeyError
dict1 = {"one": 1, "two": 2, "three": 3}

value = dict1.get("one", 111)
print(value)  # key"one"存在 default不生效 1

none_value = dict1.get("four")
print(none_value)  # key"four"不存在 None

default_value = dict1.get("four", 4)
print(default_value)  # key"four"不存在 返回default给定值 4

一般写法: 使用方括号dict1[key]直接获取,指定键

  • 若key已存在,则返回其对应的值
  • 若key不存在,则抛出KeyError
dict1 = {"one": 1, "two": 2, "three": 3}

value = dict1["one"]
print(value)  # 1

none_value = dict1["four"]  # key"four"不存在 抛出KeyError: 'four'

3) 获取键值对列表

获取(键, 值)元组列表动态视图
推荐写法: 使用Python3的标准库,dict类内置函数:items()

    • 返回Dict键值对的视图对象,当Dict更改时,会动态反映这些变化
dict1 = {"one": 1, "two": 2, "three": 3}

items = dict1.items()
print(items)  # dict_items([('one', 1), ('two', 2), ('three', 3)])

dict1.clear()
print(items)  # dict_items([])

 

4) 获取key列表

获取key列表动态视图
推荐写法: 使用Python3的标准库,dict类内置函数:keys()

    • 返回Dict键的视图对象,当Dict更改时,会动态反映这些变化
dict1 = {"one": 1, "two": 2, "three": 3}

keys = dict1.keys()
print(keys)  # dict_keys(['one', 'two', 'three'])

dict1.clear()
print(keys)  # dict_keys([])

5) 获取value列表

获取value列表动态视图
推荐写法: 使用Python3的标准库,dict类内置函数:values()

    • 返回Dict值的视图对象,当Dict更改时,会动态反映这些变化
dict1 = {"one": 1, "two": 2, "three": 3}

values = dict1.values()
print(values)  # dict_values([1, 2, 3])

dict1.clear()
print(values)  # dict_values([])

6) 从字典中提取符合条件的子集

从字典中过滤/映射符合条件的Dict
推荐写法: 使用推导式

prices = {
"a": 45.23,
"b": 612.78,
"c": 205.55,
"d": 37.20,
"e": 10.75
}

# ---过滤---
# 1. 获取value>200的键值对构成的字典
dict1 = {key: value for key, value in prices.items() if value > 200}
print(dict1)  # {'b': 612.78, 'c': 205.55}

# 2. 获取names中的key对应的键值对构成的字典
names = {"d", "e"}

# 以下方法1,2都可以满足要求,但运行时间测试结果显示,方法2比方法1所花费的时间更多。
# 方法1
dict2 = {key: value for key, value in prices.items() if key in names}
print(dict2)  # {'d': 37.2, 'e': 10.75}

# 方法2
dict3 = {key: prices[key] for key in prices.keys() & names}
print(dict3)  # {'d': 37.2, 'e': 10.75}

# ---映射---
# 1. 将value转换成整数
dict4 = {key: int(value) for key, value in prices.items()}
print(dict4)  # {'a': 45, 'b': 612, 'c': 205, 'd': 37, 'e': 10}

8. Dict判断

1) 判断key是否在字典中

判断key是否在字典中
推荐写法: 使用运算符“in”

  • 对大小写敏感
if key in dict1:
    """do something"""
if key not in dict1:
    """do something"""
    
dict1 = {"one": 1, "two": 2, "three": 3}
print("one" in dict1)  # True
print("one" not in dict1)  # False
print("One" in dict1)  # False

9. Dict排序

1) 根据key对字典排序

根据key,对字典进行排序
推荐写法: 使用Python3的标准库,内置函数:sorted(iterable[, key=None[, reverse=False]),key和reverse是可选参数

  • 返回一个排序列表
  • iterable用于指定一个可迭代对象,这里是一个字典实例
  • key用于指定排序规则,默认是None,语法是key=lambda elem:xxx
  • reverse用于指定排序方向,默认是升序,语法是reverse=False/True
dict1 = {"a": 3, "c": 1, "b": 2}

# item指代(键,值)元组,item[0]是键, item[1]是值
# 正序
dict_sorted = sorted(dict1.items(), key=lambda item: item[0])
print(dict_sorted)  # [('a', 3), ('b', 2), ('c', 1)]

# 逆序
dict_sorted_rev = sorted(dict1.items(), key=lambda item: item[0], reverse=True)
print(dict_sorted_rev)  # [('c', 1), ('b', 2), ('a', 3)]

# ------
# 注意:sorted(dict1)默认是对key排序,而不是对整个字典
sorted1 = sorted(dict1)
print(sorted1)  # ['a', 'b', 'c']

 

2) 根据key对value排序

根据字典的键,对值进行排序
推荐写法

  • 先使用内置函数sorted,根据key对字典排序
  • 再使用推导式,获取value列表
  • 关于sorted函数的用法,参看章节“根据key对字典排序”
dict1 = {"a": 3, "c": 1, "b": 2}

list1 = sorted(dict1.items(), key=lambda item: item[0])
print(list1)  # 根据key对字典排序 [('a', 3), ('b', 2), ('c', 1)]

list2 = [value for key, value in list1]
print(list2)  # [3, 2, 1]

 

推荐写法

  • 先使用内置函数sorted,对字典的键列表排序
  • 再使用推导式,获取key对应的value
dict1 = {"a": 3, "c": 1, "b": 2}
keys = sorted(dict1.keys())
list1 = [dict1[k] for k in keys]
print(list1)  # [3, 2, 1]

 

推荐写法

  • 先使用内置函数sorted,对字典的键列表排序
  • 再使用内置函数map,获取key对应的value
  • 由于Python3.x版本中,map函数的返回一个迭代器(Python2.x版本中map返回一个列表),需要使用内置类list(iterable)进行转换
dict1 = {"a": 3, "c": 1, "b": 2}
keys = sorted(dict1.keys())
list1 = list(map(dict1.get, keys))
print(list1)  # [3, 2, 1]

 

3) 根据value对字典排序

根据value,对字典进行排序
推荐写法: 使用Python3的标准库,内置函数:sorted(iterable[, key=None[, reverse=False]),key和reverse是可选参数

  • 用法同上
dict1 = {"a": 3, "c": 1, "b": 2}

# item指代(键,值)元组,item[0]是键, item[1]是值
# 正序
dict_sorted = sorted(dict1.items(), key=lambda item: item[1])
print(dict_sorted)  # [('c', 1), ('b', 2), ('a', 3)]

# 逆序
dict_sorted_rev = sorted(dict1.items(), key=lambda item: item[1], reverse=True)
print(dict_sorted_rev)  # [('a', 3), ('b', 2), ('c', 1)]

 

4) 根据某个key对应的value对字典列表排序

根据字典中某个key对应的value,对字典列表进行排序
*推荐写法: 使用Python3的标准库,operator模块的类:itemgetter(keys)

  • 需要导入operator模块的itemgetter
  • keys用于指定键,接受多个key参数,多个参数使用逗号”,“隔开
from operator import itemgetter

stu = [
    {"id": 3, "name": "Tom", "score": 82},
    {"id": 2, "name": "Jerry", "score": 67},
    {"id": 1, "name": "Pig", "score": 82},
    {"id": 4, "name": "Dog", "score": 98},
]
# 根据key"score"对应的value 对stu正序排序
'''
[{'id': 2, 'name': 'Jerry', 'score': 67},
{'id': 3, 'name': 'Tom', 'score': 82},
{'id': 1, 'name': 'Pig', 'score': 82},
{'id': 4, 'name': 'Dog', 'score': 98}]
'''

sorted_by_score = sorted(stu, key=itemgetter("score"))
print(sorted_by_score)

# 根据key"score"对应的value 对stu逆序排序
'''
[{'id': 4, 'name': 'Dog', 'score': 98},
{'id': 3, 'name': 'Tom', 'score': 82},
{'id': 1, 'name': 'Pig', 'score': 82},
{'id': 2, 'name': 'Jerry', 'score': 67}]
'''
sorted_by_score_rev = sorted(stu, key=itemgetter("score"), reverse=True)
print(sorted_by_score_rev)

# 根据key"score"和"id" 对stu正序排序(先根据"score"排序,"score"相同的情况下根据"id"排序)
'''
[{'id': 2, 'name': 'Jerry', 'score': 67},
{'id': 1, 'name': 'Pig', 'score': 82},
{'id': 3, 'name': 'Tom', 'score': 82},
{'id': 4, 'name': 'Dog', 'score': 98}]
'''
rows_by_score_id = sorted(stu, key=itemgetter("score", "id"))
print(rows_by_score_id)

 


 
 
 

 

标签:dict1,模块,Python,two,Dict,key,print,字典
来源: https://www.cnblogs.com/liuyuxuan/p/14078870.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有