首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

Python 字典

  • 23-11-14 09:22
  • 4459
  • 7508
blog.csdn.net

Python 字典

文章目录

  • Python 字典
    • 访问字典
    • 使用 `for`循环访问字典
    • 更新词典
    • 从字典中删除值
    • 检索字典键和值
    • 检查字典键
    • 多维词典
    • 内置字典方法

字典是一个无序的集合,包含用逗号分隔的花括号内的 key:value对。 字典经过优化,可以在已知关键字的情况下检索值。

下面声明一个字典对象。

Example: Dictionary

capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}
  • 1

上图,capitals是一个字典对象,其中包含{ }内部的键值对。 左侧:为按键,右侧为数值。 密钥应该是唯一且不可变的对象。数字、字符串或元组可以用作关键字。因此,以下词典也有效:

Example: Dictionary Objects

d = {} # empty dictionary

numNames={1:"One", 2: "Two", 3:"Three"} # int key, string value

decNames={1.5:"One and Half", 2.5: "Two and Half", 3.5:"Three and Half"} # float key, string value

items={("Parker","Reynolds","Camlin"):"pen", ("LG","Whirlpool","Samsung"): "Refrigerator"} # tuple key, string value

romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} # string key, int value 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

但是,以列表作为关键字的字典是无效的,因为列表是可变的:

Error: List as Dict Key

dict_obj = {["Mango","Banana"]:"Fruit", ["Blue", "Red"]:"Color"}
  • 1

但是,列表可以用作值。

Example: List as Dictionary Value

dict_obj = {"Fruit":["Mango","Banana"], "Color":["Blue", "Red"]} 
  • 1

同一个键在集合中不能出现多次。如果该密钥出现多次,将只保留最后一次。该值可以是任何数据类型。一个值可以分配给多个键。

Example: Unique Keys

>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> numNames
{1:"One", 2:"Two", 3:"Three"} 
  • 1
  • 2
  • 3

dict是所有字典的类,如下图所示。

Example: Distinct Type

>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}
>>> type(numNames)
<class 'dict'> 
  • 1
  • 2
  • 3

也可以使用 dict() 构造器方法创建字典。

Example: dict() Constructor Method

>>> emptydict = dict()
>>> emptydict
{}
>>> numdict = dict(I='one', II='two', III='three')
>>> numdict
{'I': 'one', 'II': 'two', 'III': 'three'} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

访问字典

字典是一个无序的集合,因此不能使用索引访问值;相反,必须在方括号中指定一个键,如下所示。

Example: Get Dictionary Values

>>> capitals = {"USA":"Washington DC", "France":"Paris", "India":"New Delhi"}
>>>capitals["USA"]
'''
'Washington DC'
'''
>>> capitals["France"]
'''
'Paris'
'''
>>> capitals["usa"]  # Error: Key is case-sensitive
'''
Traceback (most recent call last):
  File "", line 1, in 
    capitals['usa']
KeyError: 'usa'
'''
>>> capitals["Japan"] # Error: key must exist
'''
Traceback (most recent call last):
File "", line 1, in 
capitals['Japan']
KeyError: 'Japan' 
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

*Note:*Keys are case-sensitive. So, usa and USA are treated as different keys. If the specified key does not exist then it will raise an error. *使用 get() 方法检索键的值,即使键是未知的。 如果密钥不存在,则返回None,而不是产生错误。

Example: Get Dictionary Values

>>> capitals = {"USA":"Washington DC", "France":"Paris", "Japan":"Tokyo", "India":"New Delhi"}
>>> capitals.get("USA")
'''
'Washington DC'
'''
>>> capitals.get("France")
'''
'Paris'
'''
>>> capitals.get("usa")
>>> capitals.get("Japan")
>>> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

使用 for循环访问字典

使用 for循环迭代 Python 脚本中的字典。

Example: Access Dictionary Using For Loop

capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"}

for key in capitals:
    print("Key = " + key + ", Value = " + capitals[key]) 
  • 1
  • 2
  • 3
  • 4

Output

Key = 'USA', Value = 'Washington D.C.'
Key = 'France', Value = 'Paris'        
Key = 'India', Value = 'New Delhi' 
  • 1
  • 2
  • 3

更新词典

如前所述,密钥不能出现多次。使用相同的键并为其分配新值,以更新字典对象。

Example: Update Value of Key

>>> captains = {"England":"Root", "Australia":"Smith", "India":"Dhoni"}
>>> captains['India'] = 'Virat'
>>> captains['Australia'] = 'Paine'
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'} 
  • 1
  • 2
  • 3
  • 4
  • 5

使用新的键并为其赋值。字典将在其中显示一个额外的键值对。

Example: Add New Key-Value Pair

>>> captains['SouthAfrica']='Plessis'
>>> captains
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'SouthAfrica': 'Plessis'} 
  • 1
  • 2
  • 3

从字典中删除值

使用 del 关键字、 pop() 或 popitem() 方法从字典或字典对象本身中删除一对。要删除一对,请使用其键作为参数。 要删除字典对象,请使用其名称。

Example: Delete Key-Value

>>> captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
>>> del captains['Srilanka'] # deletes a key-value pair
>>> captains
'''
{'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'}
'''
>>> del captains # delete dict object
>>> captains
'''
NameError: name 'captains' is not defined 
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

NameError表示字典对象已经从内存中移除。

检索字典键和值

键()和值()方法分别返回包含键和值的视图对象。

Example: keys()

>>> d1 = {'name': 'Steve', 'age': 21, 'marks': 60, 'course': 'Computer Engg'}
>>> d1.keys()
'''
dict_keys(['name', 'age', 'marks', 'course'])
'''
>>> d1.values()
'''
dict_values(['Steve', 21, 60, 'Computer Engg']) 
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

检查字典键

您可以使用in或not in关键字检查字典集合中是否存在主键,如下所示。 注意,它只检查键,不检查值。

Example: Check Keys

>>> captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'}
>>> 'England' in captains
True
>>> 'India' in captains
True
>>> 'France' in captains
False
>>> 'USA' not in captains
True 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

多维词典

让我们假设有三个字典对象,如下所示:

Example: Dictionary

>>> d1={"name":"Steve","age":25, "marks":60}
>>> d2={"name":"Anil","age":23, "marks":75}
>>> d3={"name":"Asha", "age":20, "marks":70} 
  • 1
  • 2
  • 3

让我们给这些学生分配卷号,创建一个以卷号为关键字的多维字典,并根据它们的值对上述字典进行排序。

Example: Multi-dimensional Dictionary

>>> students={1:d1, 2:d2, 3:d3}
>>> students
{1: {'name': 'Steve', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23, 'marks': 75}, 3: {'name': 'Asha', 'age': 20, 'marks': 70}}< 
  • 1
  • 2
  • 3

student对象是一个二维字典。这里d1、d2和d3分别被指定为键 1、2 和 3 的值。students[1]返回d1。

Example: Access Multi-dimensional Dictionary

>>> students[1]
{'name': 'Steve', 'age': 25, 'marks': 60}
>>> students[1]['age']
25 
  • 1
  • 2
  • 3
  • 4

内置字典方法

方法描述
dict.clear()从字典中移除所有键值对。
dict.copy()返回字典的一个简单副本。
发布 fromkeys()从给定的可迭代表(字符串、列表、集合、元组)创建一个新的字典作为键,并使用指定的值。
dict.get()返回指定键的值。
dict.items()返回字典视图对象,该对象以键值对列表的形式提供字典元素的动态视图。当字典改变时,这个视图对象也随之改变。
dict . key()返回包含字典键列表的字典视图对象。
dict.pop()移除键并返回其值。如果字典中不存在某个键,则返回默认值(如果指定的话),否则将引发键错误。
关闭。泼皮()从字典中移除并返回(键、值)对的元组。成对按后进先出(后进先出)顺序返回。
dict.setdefault()返回字典中指定键的值。如果找不到该键,则添加具有指定 defaultvalue 的键。如果未指定默认值,则设置为无值。
dict.update()使用来自另一个字典或另一个表(如具有键值对的元组)的键值对更新字典。
字典值()返回字典视图对象,该对象提供字典中所有值的动态视图。当字典 改变时,这个视图对象改变。

《AUTOSAR谱系分解(ETAS工具链)》之总目录

注:本文转载自blog.csdn.net的PlutoZuo的文章"https://blog.csdn.net/PlutoZuo/article/details/133042077"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top