Python中字典的相关操作
1. Python类似于Java中的哈希表,只是两种语言表示的方式是不一样的,Python中的字典定义如下:
在Python中是一种可变的容器模型,它是通过一组键(key)值(value)对组成,这种结构类型通常也被称为映射,或者叫关联数组,也有叫哈希表的。每个key-value之间用 " : " 隔开,每组用","分割,整个字典用"{}"括起来(实际上就是一种映射关系)
2. 下面是关于字典的一些常用的操作:
① 创建字典,常用的主要有以下三种方式:
除了直接用大括号创建字典,还可以用dict( )来创建字典
用法如下:
通过放入列表套元组或者元组套列表实现
或者列表套列表 、元组套元组
具体的代码如下:
# -*- coding: utf-8 -*-
"""
Created on Fri May 17 21:08:34 2019
"""
di = dict([('one', 1), ('two', 2), ('three', 3),('three', 4),('three', 5)])
print(di)
print('-' * 20, "\n")
di = dict((('one', 1), ('two', 2)))
print(di)
print('-' * 20, "\n")
di = dict([['one', 1], ['two1', 2]])
print(di)
print('-' * 20, "\n")
② 对字典进行遍历
for key in dict2:
print(key)
print('-' * 20, "\n")
for key in dict2.keys():
print(key)
print('-' * 20, "\n")
for value in dict2.values():
print(value)
print('-' * 20, "\n")
for key in dict2:
print('%s--%s' %(key,dict2[key]))
print('-' * 20, "\n")
#这样遍历获取到的是一个元祖
for i in dict3.items():
print(i)
print(i[0])
print('-' * 20, "\n")
③ dict.clear()
作用:删除字典中的所有项或元素,无返回值(注意,不是删除字典,而是清空字典内容)
④ dict.get(key , default=None)
作用:返回字典中key对应的值,若key不存在,则返回default的值(default默认为None)
⑤ dict.pop(key [,default])
作用:如果字典中存在key,则删除并返回key对应的value;如果key不存在,且没有给出default值,则引发KeyError异常
⑥ dict.setdefault(key , default = None)
作用:如果字典不存在key,则由dict[key] = default为其赋值
⑦ dict.update(adict)
作用:将字典adict中键值对添加到dict中
3. 具体的代码如下:
# -*- coding: utf-8 -*-
"""
Created on Fri May 17 16:59:11 2019
"""
#划重点:键必须是唯一的,必须是不可变的,如字符串,数字,元组
#值可以是任何数据类型
#这让我想到了Java中的哈希表
#1.创建字典
dict1 = {1: 'zhangsan', 2: 'lisi'}
print(dict1)
print(type(dict1))
dict2 = {'name1': 'zhangsan', 'name2': 'lisi'}
#除了直接用大括号创建字典,还可以用dict()来创建字典
#用法如下:
#通过放入列表套元组或者元组套列表实现
#或者列表套列表 、元组套元组
#还记得上节课在元组里讲到的列表和元组的相互转换么?
#使用dict来创建字典
#下面来遍历一下字典中的元素
for key in dict2:
print(key)
print('-' * 20, "\n")
for key in dict2.keys():
print(key)
print('-' * 20, "\n")
for value in dict2.values():
print(value)
print('-' * 20, "\n")
#遍历
for key in dict2:
# 注意在使用输出语句的时候不能够使用逗号
print('%s--%s' %(key,dict2[key]))
print('-' * 20, "\n")
#对于字典的操作
#1.dict.keys()
#作用:返回包含字典所有key的列表
#2.dict.values()
#作用:返回包含字典所有value的列表
#3.dict.items()
#作用:返回包含所有(键,值)项的列表
dict3 = {'xiaoming': 12, 'xiaozhang': 20, 'xiqiaing' : 21}
for i in dict3.items():
#这样遍历获取到的是一个元祖所以我们可以按照取出元祖的方式来取出相应的元素
print(i)
#取出元祖中的第一个元素
print(i[0])
# print(type(i))
print('-' * 20, "\n")
#4.dict.clear()
#作用:删除字典中的所有项或元素,无返回值(注意,不是删除字典,而是清空字典内容)
dict2.clear()
print(dict2)
print('-' * 20, "\n")
#5.dict.get(key , default=None)
#作用:返回字典中key对应的值,若key不存在,则返回default的值(default默认为None)
print(dict3.get('xiaoming'))
print('-' * 20, "\n")
#6.dict.pop(key [,default])
#作用:如果字典中存在key,则删除并返回key对应的value;如果key不存在,且没有给出default值,则引发KeyError异常
print(dict3.pop('xiqiaing'))
print(dict3)
print('-' * 20, "\n")
#7.dict.setdefault(key , default = None)
#作用:如果字典不存在key,则由dict[key] = default为其赋值
dict3.setdefault('xiqiaing', 22)
print(dict3)
#8.dict.update(adict)
#作用:将字典adict中键值对添加到dict中
dict3.update(dict1)
print(dict3)
---------------------
Python中字典的相关操作的更多相关文章
- python的字典及相关操作
一.什么是字典 字典是Python中最强大的数据类型之一,也是Python语言中唯一的映射类型.映射类型对象里哈希值(键,key)和指向的对象(值,value)是一对多的的关系,通常被认为是可变的哈希 ...
- python之字典的相关操作
一.什么是字典 dict 用{}表示,用来存放键值对数据 {key:value} 键:具有唯一性,不能重复,不可变 必须是可哈希的(不可变的数据类型) 字典是无序的,没有索引 值: 没有任何限制 已知 ...
- python中字典数据类型常用操作
创建字典 字典是另一种可变容器模型,且可存储任意类型对象. 字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示: ...
- python中字典dict的操作
字典可存储任意类型的对象,由键和值(key - value)组成.字典也叫关联数组或哈希表. dict = {' , 'C' : [1 , 2 , 3] } dict['A'] = 007 # 修改字 ...
- python中字典的基础操作
dict1 = { 'name':'王麻子', 'age':25, 'phone':12580, 'high':160 } dict2 = { 'name':'张三', 'age':38, 'phon ...
- 三十三、python中configparser配置文件相关操作
配置文件ini [a1]age = 18sex = 'man' [a2]age = 19sex = 'woman'name = False 1.对配置文件进行操作 import configparse ...
- Python中字典和集合
Python中字典和集合 映射类型: 表示一个任意对象的集合,且可以通过另一个几乎是任意键值的集合进行索引 与序列不同,映射是无序的,通过键进行索引 任何不可变对象都可用作字典的键,如字符串.数字.元 ...
- 【转】python 历险记(四)— python 中常用的 json 操作
[转]python 历险记(四)— python 中常用的 json 操作 目录 引言 基础知识 什么是 JSON? JSON 的语法 JSON 对象有哪些特点? JSON 数组有哪些特点? 什么是编 ...
- 在Python中使用lambda高效操作列表的教程
在Python中使用lambda高效操作列表的教程 这篇文章主要介绍了在Python中使用lambda高效操作列表的教程,结合了包括map.filter.reduce.sorted等函数,需要的朋友可 ...
随机推荐
- [poj1698]Alice's Chance[网络流]
[转]原文:http://blog.csdn.net/wangjian8006/article/details/7926040 题目大意:爱丽丝要拍电影,有n部电影,规定爱丽丝每部电影在每个礼拜只有固 ...
- Postgres 数据库字符集更改 ERROR: new encoding (UTF8) is incompatible
https://blog.csdn.net/hkyw000/article/details/52817422 http://www.cnblogs.com/taosim/articles/438329 ...
- hdu_1065_I Think I Need a Houseboat_201311160023
I Think I Need a Houseboat Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Ja ...
- [poj3070]Fibonacci_矩乘_快速幂
Fibonacci poj-3070 题目大意:求Fibonacci第n项. 注释:模数为10000,$1\le n \le 10^9$. 想法:矩阵题,用例题6的想法,我们构造矩阵 $\begin{ ...
- Spring MVC-视图解析器(View Resolverr)-资源包视图解析器(Resource Bundle View Resolver)示例(转载实践)
以下内容翻译自:https://www.tutorialspoint.com/springmvc/springmvc_resourcebundleviewresolver.htm 说明:示例基于Spr ...
- windows与linux下配置ant
转自:http://www.cnblogs.com/wuxinrui/archive/2012/01/06/2314392.html 1.下载:到ANT官方网站http://ant.apache.or ...
- GDB 调试 PHP文件
http://www.bo56.com/%E5%9C%A82016%E7%9A%84phpcon%E5%A4%A7%E4%BC%9A%E4%B8%8A%E7%9A%84%E5%88%86%E4%BA% ...
- 2.5-冗余VLAN
2.5-冗余VLAN High-Availability(AH) First hop routers on the LAN redundancy Network/首跳冗余网络(出口第一个网络) ...
- 设计模式实例(Lua)笔记之五(Bridge模式)
1.描写叙述 今天我要说说我自己,梦想中的我自己,我身价过亿,有两个大公司,一个是房地产公司,一个是服装制造业,这两个公司都非常赚钱,天天帮我在累加財富,事实上是什么公司我倒是不关心,我关心的是是不是 ...
- spring主要产品
Spring Framework * Spring Web Flow * Spring Web Services * Spring Security (Acegi Security) ...