Python字典(Dictionary)(Python字典中的值不允许重复吗)
off999 2024-11-02 12:32 24 浏览 0 评论
Python中的Dictionary是数据值的无序集合,用于存储数据值(如映射),与其他仅将单个值作为元素的数据类型不同,Dictionary拥有key:value对。字典中提供了键值以使其更优化。
创建字典
在Python中,可以通过将元素序列放在大括号中(用逗号分隔)来创建字典。Dictionary保存一对值,一个是Key,另一个对应的pair元素是它的Key:value。字典中的值可以是任何数据类型并且可以重复,而键不能重复并且必须是不可变的。
注意:字典键区分大小写,名称相同,但键的大小写会被区别对待。
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
输出:
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
字典也可以由内置函数dict()创建。只需放置到大括号{}即可创建空字典。
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
输出:
Empty Dictionary:
{}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}
嵌套字典:
# Creating a Nested Dictionary
# as shown in the below image
Dict = {1: 'Geeks', 2: 'For',
3:{'A' : 'Welcome', 'B' : 'To', 'C' : 'Geeks'}}
print(Dict)
输出:
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
向字典添加元素
在Python字典中,可以通过多种方式添加元素。一次只能添加一个值到字典中,方法是定义值和键,例如Dict[key]=“value”。可以使用内置的update()方法更新字典中的现有值。嵌套的键值也可以添加到现有字典中。
注意:在添加值时,如果键值已经存在,则会更新该值,否则会向字典中添加具有该值的新键。
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}}
print("\nAdding a Nested Key: ")
print(Dict)
输出:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'Geeks', 2: 'Welcome', 3: 1, 5: {'Nested': {'1': 'Life', '2': 'Geeks'}}, 'Value_set': (2, 3, 4)}
从字典访问元素
要访问字典的项,请参阅字典的键名。可以在方括号内使用键。
# Python program to demonstrate
# accessing a element from a Dictionary
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])
# accessing a element using key
print("Accessing a element using key:")
print(Dict[1])
输出:
Accessing a element using key:
For
Accessing a element using key:
Geeks
还有一个名为get()的方法也有助于访问字典中的元素。
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using get()
# method
print("Accessing a element using get:")
print(Dict.get(3))
输出:
Accessing a element using get:
Geeks
访问嵌套字典的元素
要访问嵌套字典中任何键的值,请使用index[]语法。
# Creating a Dictionary
Dict = {'Dict1': {1: 'Geeks'},
'Dict2': {'Name': 'For'}}
# Accessing element using key
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
输出:
{1: 'Geeks'}
Geeks
For
从字典中删除元素
使用del关键字
在Python字典中,可以使用del关键字来删除键。使用del关键字,可以删除字典和整个字典中的特定值。嵌套字典中的项也可以通过使用del关键字并提供特定的嵌套键和要从该嵌套字典中删除的特定键来删除。
注意:del Dict将删除整个字典,因此在删除后打印它将导致错误。
# Initial Dictionary
Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks',
'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'},
'B' : {1 : 'Geeks', 2 : 'Life'}}
print("Initial Dictionary: ")
print(Dict)
# Deleting a Key value
del Dict[6]
print("\nDeleting a specific key: ")
print(Dict)
# Deleting a Key from
# Nested Dictionary
del Dict['A'][2]
print("\nDeleting a key from Nested Dictionary: ")
print(Dict)
输出:
Initial Dictionary:
{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 6: 'To', 7: 'Geeks'}
Deleting a specific key:
{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 7: 'Geeks'}
Deleting a key from Nested Dictionary:
{'A': {1: 'Geeks', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 7: 'Geeks'}
使用pop()方法
Pop()方法用于返回和删除指定键的值。
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Deleting a key
# using pop() method
pop_ele = Dict.pop(1)
print('\nDictionary after deletion: ' + str(Dict))
print('Value associated to poped key is: ' + str(pop_ele))
输出:
Dictionary after deletion: {3: 'Geeks', 'name': 'For'}
Value associated to poped key is: Geeks
使用popitem()方法
popitem()返回并从字典中删除一个任意元素(键,值)对。
# Creating Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Deleting an arbitrary key
# using popitem() function
pop_ele = Dict.popitem()
print("\nDictionary after deletion: " + str(Dict))
print("The arbitrary pair returned is: " + str(pop_ele))
输出:
Dictionary after deletion: {3: 'Geeks', 'name': 'For'}
The arbitrary pair returned is: (1, 'Geeks')
使用clear()方法
使用clear()方法可以一次删除字典中的所有项。
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Deleting entire Dictionary
Dict.clear()
print("\nDeleting Entire Dictionary: ")
print(Dict)
输出:
Deleting Entire Dictionary:
{}
词典方法
相关推荐
- 一文搞清 Python 中方法和函数之间的区别
-
在我们使用Python的过程中,经常涉及到方法和函数,那他们有什么不同吗?在本文中,让我们通过示例了解Python中方法和函数之间的区别。Python函数Python函数是一系列以特定顺序...
- Python 数据分析 + 可视化实战:5 分钟出图表,老板看了直点赞
-
还在用Excel做数据分析?效率太低了!同样一份销售数据,同事用Python半小时出报告,图表炫酷还能自动更新;你用Excel捣鼓大半天,稍微改点数据就得重新做图。今天教你用Python...
- Python每日一库之Pendulum(python penup)
-
关于日期处理,Python提供了许多库,例如标准库datetime、第三方库dateutil、Arrow等。在这篇文章中,我想介绍我个人最喜欢的库pendulum,它使用非常方便,它可以满足...
- Python计算两个日期相差天数 M + ACT/360模式,银行计算利息用
-
一般银行在计算计息的时候,都会用到M+ACT/360模式,也就是满1个月按30天计算,不足一个月按实际天数计算。一年算360天。例如:计算20151018到20190817相差的天数,201...
- Python 之 MySql 每日一练 32——查询每门课程的平均成绩
-
一、表名和字段–1.学生表student(s_id,s_name,s_birth,s_sex)–学生编号,学生姓名,出生年月,学生性别–2.课程表course(c_id,c_name,t...
- 用Python制作数据报告:如何自动生成PDF格式的报告?
-
最近在琢磨数据分析工作的自动化,手动做报告真是太费劲啦!试过用Python整了个自动生成PDF报告的小工具,效果还不错。今天就聊聊怎么用Python把数据处理、可视化和PDF生成一条龙搞定。repor...
- Github 1.2k star,一个好用的 Python 库-pyexcel!
-
大家好,今天为大家分享一个好用的Python库-pyexcel。Github地址:https://github.com/pyexcel/pyexcelpyexcel是一个功能强大的Python...
- 使用python写一个简单的到期事件钉钉提醒功能
-
前言:学习python第3天需求:简单的事件提醒功能版本:python3.9、mysql5.71、现在mysql建一个表event_remindCREATETABLE`event_remind`...
- python定时任务最强框架APScheduler详细教程
-
APScheduler定时任务上次测试女神听了我的建议,已经做好了要给项目添加定时任务的决定了。但是之前提供的四种方式中,她不知道具体选择哪一个。为了和女神更近一步,我把我入行近10年收藏的干货免费拿...
- 解放双手,一键运行!Python每日自动生成数据日报
-
对于一个企业来说,高层看意义,中层看结论,基层看落地,数据日报、周报、月报可以监控销售个人在实际执行过程中的销售动态,而数据季度报、年报可以反映一个销售策略是否与实际的业务场景切合。可见数据日报在我们...
- Python模块datetime、calendar、logging、argparse、re用法
-
datetime模块:提供日期和时间相关的功能。importdatetime#获取当前日期和时间current_time=datetime.datetime.now()#格式化日期...
- python入门到脱坑正则表达式—re.search()函数
-
re.search()是Python正则表达式模块re中的核心函数之一,用于在字符串中搜索匹配指定模式的第一个位置。与re.match()不同,它不限制匹配必须从字符串开头开始。基本语法...
- python3从零学习-5.2.1、日历相关模块calendar
-
源代码:Lib/calendar.py这个模块让你可以输出像Unixcal那样的日历,它还提供了其它与日历相关的实用函数。默认情况下,这些日历把星期一当作一周的第一天,星期天为一周的最后一...
- DAY6-step7 Python 示例说明CALENDAR
-
Python中的Calendar模块具有Calendar类,该类允许基于日期,月份和年份来计算各种任务。最重要的是,Python中的TextCalendar和HTMLCalendar类允许您编辑日历...
- Python 数据分析——Pandas 时间序列
-
Pandas提供了表示时间点、时间段和时间间隔等三种与时间有关的类型,以及元素为这些类型的索引对象,并提供了许多时间序列相关的函数。一、时间点、时间段、时间间隔Timestamp对象从Python标准...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- 一文搞清 Python 中方法和函数之间的区别
- Python 数据分析 + 可视化实战:5 分钟出图表,老板看了直点赞
- Python每日一库之Pendulum(python penup)
- Python计算两个日期相差天数 M + ACT/360模式,银行计算利息用
- Python 之 MySql 每日一练 32——查询每门课程的平均成绩
- 用Python制作数据报告:如何自动生成PDF格式的报告?
- Github 1.2k star,一个好用的 Python 库-pyexcel!
- 使用python写一个简单的到期事件钉钉提醒功能
- python定时任务最强框架APScheduler详细教程
- 解放双手,一键运行!Python每日自动生成数据日报
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python字典遍历 (54)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python读取文件夹下所有文件 (59)
- java调用python脚本 (56)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)