首页 > 编程语言 >python基础之字典 Dictionary

python基础之字典 Dictionary

时间:2023-11-16 17:22:07浏览次数:31  
标签:name Dictionary python person dict 键值 字典 Out

   

字典 Dictionary

在Python中,字典(Dictionary)是一种无序的、可变的数据类型,用于存储键-值(key-value)对的集合。字典是通过键来索引和访问值的,而不是通过位置。

字典 dictionary ,在一些编程语言中也称为 hash , map ,是一种由键值对组成的数据结构。

   

基本操作

   

python{}或者dict()来创建声明一个空字典

  In [2]:
d = {}
type(d)
  Out[2]:
dict
  In [7]:
d = dict()
type(d)
  Out[7]:
dict
  In [8]:
# {}初始化一个字典
b = {'one':10,'two':2,'name':'wang'}
b
  Out[8]:
{'one': 10, 'two': 2, 'name': 'wang'}
  In [10]:
# dict()初始化一个字典
b = dict(
    [('foozelator', 123),
     ('frombicator', 18), 
     ('spatzleblock', 34), 
     ('snitzelhogen', 23)
    ])
b
  Out[10]:
{'foozelator': 123, 'frombicator': 18, 'spatzleblock': 34, 'snitzelhogen': 23}
   

新增值

  In [4]:
d['name'] = 'dog'
d['age'] = 20
d
  Out[4]:
{'name': 'dog', 'age': 20}
   

查看键值

  In [5]:
d['name']
  Out[5]:
'dog'
   

修改值

  In [6]:
d['name'] = 'xiao ming'
d
  Out[6]:
{'name': 'xiao ming', 'age': 20}
   

字典是没有顺序的,因此,Python中不能用支持用数字索引按顺序查看字典中的值,而且数字本身也有可能成为键值,这样会引起混淆:

  In [9]:
# 报错
d[0]
   
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[9], line 1
----> 1 d[0]

KeyError: 0
   

字典的键类型

出于hash的目的,Python中要求这些键值对的键必须是不可变的,而值可以是任意的Python对象。

  In [11]:
# 字典中的数组
d = {}
d['mutable'] = ['changeable', 'variable', 'varying', 'fluctuating',
                       'shifting', 'inconsistent', 'unpredictable', 'inconstant',
                       'fickle', 'uneven', 'unstable', 'protean']
d['immutable'] = ['fixed', 'set', 'rigid', 'inflexible', 
                         'permanent', 'established', 'carved in stone']
d
  Out[11]:
{'mutable': ['changeable',
  'variable',
  'varying',
  'fluctuating',
  'shifting',
  'inconsistent',
  'unpredictable',
  'inconstant',
  'fickle',
  'uneven',
  'unstable',
  'protean'],
 'immutable': ['fixed',
  'set',
  'rigid',
  'inflexible',
  'permanent',
  'established',
  'carved in stone']}
  In [13]:
# 定义4个字典
e1 = {'mag': 0.05, 'width': 20, 'name':'dog'}
e2 = {'mag': 0.04, 'width': 25}
e3 = {'mag': 0.05, 'width': 80}
e4 = {'mag': 0.03, 'width': 30}

events = {1:e1, 2:e2, 3:e3, 4:e4}
events
  Out[13]:
{1: {'mag': 0.05, 'width': 20, 'name': 'dog'},
 2: {'mag': 0.04, 'width': 25},
 3: {'mag': 0.05, 'width': 80},
 4: {'mag': 0.03, 'width': 30}}
   

有时候,也可以使用元组作为键值,例如,可以用元组做键来表示从第一个城市飞往第二个城市航班数的多少:

  In [22]:
connections = {}
connections[('New York', 'Seattle')] = 100
connections[('Austin', 'New York')] = 200
connections[('New York', 'Austin')] = 400

print(connections[('New York', 'Seattle')])
print(connections[('Austin', 'New York')])
   
100
200
   

字典的方法

   

get()方法

用索引可以找到一个键对应的值,但是如果键不存在,python会报错,这个时候就可以使用get()方法来处理这种情况,使用如下:

d.get(key, default = None)

  In [23]:
d = {'one':'a','two':2}
d['three']
   
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[23], line 2
      1 d = {'one':'a','two':2}
----> 2 d['three']

KeyError: 'three'
  In [25]:
print(d.get('three'))
   
None
  In [29]:
print(d.get('three', 3))
   
3
   

pop()方法

pop方法可以弹出字典中某个键对应的值,同时也可以指定默认参数:

dict.pop(key, default=None)

删除并返回字典中key对应的值,如果没有这个key,则返回指定的默认值

  In [36]:
d = {'one':'a','two':2}
d.pop('one')
print(d)
   
{'two': 2}
  In [37]:
d.pop('three', 3)
  Out[37]:
3
  In [38]:
# 与列表一样,del 函数可以用来删除字典中特定的键值对,例如:
del d['two']
print(d)
   
{}
   

update()方法更新字典

可以通过索引来插入、修改单个键值对,但是如果想对多个键值对进行操作,这种方法就显得比较麻烦,好在有 update 方法:

dict.update(newd)

  In [39]:
person = {'first':'jm', 'last':'tom', 'born':'1990'}
print(person)
person.update({'first':'xiaoming', 'born':'2014'})
print(person)
   
{'first': 'jm', 'last': 'tom', 'born': '1990'}
{'first': 'xiaoming', 'last': 'tom', 'born': '2014'}
   

in查询字典中是否存在该键

  In [41]:
person = {'first':'jm', 'last':'tom', 'born':'1990'}
'first' in person
  Out[41]:
True
  In [42]:
'name' in person
  Out[42]:
False
   

keys()、values()和items()方法

d.keys() 返回一个由所有键组成的列表;

d.values() 返回一个由所有值组成的列表;

d.items() 返回一个由所有键值对元组组成的列表;

  In [43]:
person= {'first':'jm', 'last':'tom', 'born':'1990'}
person.keys()
  Out[43]:
dict_keys(['first', 'last', 'born'])
  In [44]:
person.values()
  Out[44]:
dict_values(['jm', 'tom', '1990'])
  In [45]:
person.items()
  Out[45]:
dict_items([('first', 'jm'), ('last', 'tom'), ('born', '1990')])


源码下载:

链接:https://pan.baidu.com/s/1UAKVxkmPWafse8Yq5tYKQA
提取码:upxl

标签:name,Dictionary,python,person,dict,键值,字典,Out
From: https://www.cnblogs.com/abc19830814/p/17836802.html

相关文章

  • C++调用python踩坑记录
     目录0、参考文档及博客1、环境配置步骤2、C++调用python的方法代码框架:(同样来源于上面这篇博客,可用于测试环境配置成功与否)报错处理函数(1)处理方法一:PyErr_Print(2)处理方法二:PyErr_Fetch2.5、终极解决方案3、踩坑记录(1)python第三方库调用出错(2)python模块环......
  • 《流畅的Python》 读书笔记 第8章_对象引用、可变性和垃圾回收
    第8章_对象引用、可变性和垃圾回收本章的主题是对象与对象名称之间的区别。名称不是对象,而是单独的东西name='wuxianfeng'#name是对象名称'wuxianfeng'是个str对象variablesarelabels,notboxes变量是标注,而不是盒子引用式变量的名称解释本章还会讨论标识......
  • python生成 时间戳和日期格式
    1.获取当前日期要获取当前日期,我们可以使用datetime模块中的datetime类的now()方法。下面是获取当前日期的代码示例:importdatetimecurrent_date=datetime.datetime.now().date()print("当前日期:",current_date)#运行以上代码,输出的结果类似于:当前日期:2022-01-01#获取时......
  • Python的txt文本操作-读、写
    ✅作者简介:热爱科研的算法开发者,Python、Matlab项目可交流、沟通、学习。......
  • python调用ffmpeg循环播放一个文件夹内的视频,如果播放中断了,下次继续播放可以从上次播
    importosimportsubprocessdefplay_videos_in_folder(folder_path):#获取所有视频文件files=[os.path.join(folder_path,f)forfinos.listdir(folder_path)iff.endswith(('.mp4','.mkv'))]idx=0#视频文件索引whileTrue:......
  • Python 在PDF中生成水印
    前言在PDF中插入水印是比较常用的一种功能。一般在生成比较重要的,或者需要注明版权、作者的文档时使用比较多。这里我将分享一个通过python代码为PDF文档添加水印的办法(包括文本水印和图像水印)。这种方法也适用于批量添加水印的情况。所需工具:这个方法将用到以下程序和组件V......
  • 1-3 Python基础语法
    ​ 目录1.循环语句1.1循环语句基本使用1.2综合案例1.3break1.4continue1.5whileelse2.字符串格式化2.1%2.1.1基本格式化操作2.1.2百分比2.2format(推荐)2.3f3.运算符3.1运算符优先级3.2判断题 1.循环语句while循环for循环```while条件: ......
  • 1-2 Python基础语法
    ​ 1.编码计算机所有的数据本质上是以0和1的组合来存储在计算机中会将中文转换为0101010100最终存储到硬盘上计算机中有一个编码的概念(也就是密码本)  武  ->   0111111100011010010110110在计算机中有很多种编码每种编码都有自己的一套密码本,都维护这......
  • python3 json.dumps(OrderDict类型) 报错:TypeError: Object of type datetime is not
    chatgpt给出的解决方案,在json.dumps()函数调用中传入default参数来指定如何处理datetime对象importjsonfromdatetimeimportdatetimedefdatetime_handler(obj):ifisinstance(obj,datetime):returnobj.__str__()#另一种处理,转换为自定义格式化字符串......
  • [940] Create a progress bar in Python
    TocreateaprogressbarinPython,youcanusethetqdmlibrary,whichisapopularlibraryforaddingprogressbarstoyourloops.Ifyouhaven'tinstalledityet,youcandosousing:pipinstalltqdmHere'sasimpleexampleofhowtousetqd......