python之Dict操作(中)

python之Dict操作(中)

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)

*推荐写法: 使用Python3的标准库,内置函数:sorted(iterable, , key=None, reverse=False)

  • 接受多个key参数,多个参数使用逗号”,“隔开
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值