1. 字典和列表的区别

  对于列表,它是一些项的有序排列,只能通过数值来进行索引;对于字典,则可以通过许多东西进行索引,它采用键-值映射的方式,不存在一个特定的顺序,因此不能用类似列表的数值索引,但它的键可以是数值。

 stuff = {'name':'zed','age':18,'weight':'50kg'}
print(stuff['name'])
print(stuff['age'])
stuff['age'] = 40
print(stuff["age"])
stuff[1] = 'test' # 在列表中创建一个新的键值对
print(stuff[1])
print(stuff)

  输出为

zed
18
40
test
{'name': 'zed', 'age': 40, 'weight': '50kg', 1: 'test'}

  2. 删除字典中的内容

  del dict['key_name']

  3. 编程练习

 # create a mapping of state to abbreviation
states = {
'Oregon':'OR',
'Florida':'FL',
'California':'CA',
'New York':'NY',
'Michigan':'MI'
} # create a basic set of states and some cities in them
cities = {
'CA':'San Francisco',
'MI':'Detroit',
'FL':'Jacksonville'
} # add some mor cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland' # print out some cities
print('-' * 10)
print("NY state has: ",cities['NY'])
print("OR state has: ",cities['OR']) # print some states
print('-' * 10)
print("Michigan's abbreviation is: ",states['Michigan'])
print("Florida's abbreviation is: ",states['Florida']) # do it by using the sate then cities dict
print('-' * 10)
print("Michigan has: ", cities[states['Michigan']])
print("Florida has: ", cities[states['Florida']]) # print every state abbreviation
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} is abbreviated as {abbrev}.") # print every city in state
print('-' * 10)
for abbrev, city in list(cities.items()):
print(f"{abbrev} has the city {city}.") # now do both at the same time
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} is abbreviated as {abbrev} and has city {cities[abbrev]}") print('-' * 10)
# safely get a abbreviation by state that might not be there
state = states.get('Texas') if not state:
print(f'Sorry, no Texas.') # get a city with a default value
city = cities.get('Tx','Does not exist')
print(f"The city for the state 'TX' is: {city}")

  输出

----------
NY state has: New York
OR state has: Portland
----------
Michigan's abbreviation is: MI
Florida's abbreviation is: FL
----------
Michigan has: Detroit
Florida has: Jacksonville
----------
Oregon is abbreviated as OR.
Florida is abbreviated as FL.
California is abbreviated as CA.
New York is abbreviated as NY.
Michigan is abbreviated as MI.
----------
CA has the city San Francisco.
MI has the city Detroit.
FL has the city Jacksonville.
NY has the city New York.
OR has the city Portland.
----------
Oregon is abbreviated as OR and has city Portland
Florida is abbreviated as FL and has city Jacksonville
California is abbreviated as CA and has city San Francisco
New York is abbreviated as NY and has city New York
Michigan is abbreviated as MI and has city Detroit
----------
Sorry, no Texas.
The city for the state 'TX' is: Does not exist

  4. 上述练习中的语法点

  ① 向字典中添加键值对

dict['key'] = value

  ② 字典的嵌套

  例如dict1的值是dict2的键时,可以做如下嵌套

dict2[dict1['key1']]

  ③ dict.items()函数

  以列表的形式返回可遍历的(键,值)元组数组。

  参数:无。

  书中所用加list()的形式和不加list()实现的功能似乎一致。

 states = {
'Oregon':'OR',
'Florida':'FL',
'California':'CA',
'New York':'NY',
'Michigan':'MI'
} for state, abbr in states.items():
print(state,abbr) for state, abbr in list(states.items()):
print(state,abbr)

  ④ dict.get()函数

  用于返回dict中指定键的值,如果键不在dict中,则返回设置的默认值,语法如下

dict.get(key, default = None)
dict.get('TX', 'Does not exist.')

  5. 字典键的特性

  字典的值可以是python中的任何数据类型,也可以是用户自定义的,但字典的键不行。

  ① 字典的键不可以重复定义,如果一个键在字典中被定义两次,则只会记住最后一个值,如

 dict = {'name':'Tom','age':18,'height':'170 cm','name':'Jerry'}
print("dict['name']: {}".format(dict['name']))

  输出为

dict['name']: Jerry

  ② 字典的值必须是不可变的,因此只能使用数值,字符串或者元组,而不能使用列表,如

 dict = {['name']:'Tom','age':18,'height':'170 cm'}
print("dict[['name']]: {}".format(dict[['name']]))

  报错

Traceback (most recent call last):
File "ex23.py", line 1, in <module>
dict = {['name']:'Tom','age':18,'height':'170 cm'}
TypeError: unhashable type: 'list'

  6.字典的内置函数

  len(dict): 求字典长度

  str(dict): 以可打印的字符串的形式返回列表

  type(variable): 返回输入变量的类型,对字典就是<class 'dict'>

  7. 字典的常用操作

  dict.clear()  删除字典中所有元素

  dict.copy()  返回一个字典的浅复制 【参考】直接赋值和copy的区别

  dict.fromkeys(sequence[, value]) 创建一个新的字典,以序列sequence中的元素做字典的键,value为所有键对应的初始值

   key in dict 如果key在dict中,返回True,否则返回False

  dict.keys() 返回一个由所有键组成的迭代器,可以用list转换为列表(注意与dict.items()的区别,items()是直接返回列表)

  dictl.values() 返回一个由所有值组成的迭代器,可以用list转换为列表

  dict.setdefault(key, default = None) 和dict.get()类似,但如果key不在dict中则会添加这个键并将其值设为default

  dict1.update(dict2) 用dict2的键值对更新dict1

  dict.pop(key[,default]) 删除字典中给定key所给定的值,返回被删除的值;如果key不存在,则必须设定default的值(否则报错),并且函数将返回default的值

  8. dict.popitem() 详解

  官方文档:“Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order. ”

       "Changed in version 3.7: LIFO order is now guaranteed. In prior versions, popitem() would return an arbitrary key/value pair."

  在3.7版本以前,popitem是按所谓的“随机”顺序从字典中取出值的。在3.7以后的版本,官方文档对此作出了修改,明确指出popitem()是按照“后进先出”的顺序取出并返回字典中的键值对的。也就是说,其返回的是最后一个被添加到字典中的键值对。

 dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(dict)
print(dict.popitem())
print(dict)
dict['e'] = 5
print(dict.popitem())

  输出为

{'a': 1, 'b': 2, 'c': 3, 'd': 4}
('d', 4)
{'a': 1, 'b': 2, 'c': 3}
('e', 5)

  9. get()  pop()  popitem() 的安全性讨论

  get() 可以为key设定缺省值,也可以不设定。当没有设置default时,如果dict中没有输入的key,则返回default的缺省值None;是一种相对安全的方法。 

  pop()也可以设定缺省值,如果不设定,而key又不存在于dict中,则也会报错。

  popitem()不能设定缺省值,如果dict为空时,dict.popitem()会报错:KeyError

  

【Python基础】lpthw - Exercise 39 字典的更多相关文章

  1. python基础一数据类型之字典

    摘要: python基础一数据类型之一字典,这篇主要讲字典. 1,定义字典 2,字典的基础知识 3,字典的方法 1,定义字典 1,定义1个空字典 dict1 = {} 2,定义字典 dict1 = d ...

  2. Day2 - Python基础2 列表、字典、集合

    Python之路,Day2 - Python基础2   本节内容 列表.元组操作 字符串操作 字典操作 集合操作 文件操作 字符编码与转码 1. 列表.元组操作 列表是我们最以后最常用的数据类型之一, ...

  3. python基础之列表、字典、元祖等 (二)

    一.作用域 if 1==1: name = 'weibinf' print name 下面的结论对吗? 外层变量,可以被内层变量使用 内层变量,无法被外层变量使用 二.三元运算 result = 值1 ...

  4. python 基础之第八天--字典相关

    zx #####################创建字典###################################### In [11]: dict([('name','bob'),('a ...

  5. Python基础:映射(字典)

    一.概述 映射类型(Mapping Types)是一种关联式的容器类型,它存储了对象与对象之间的映射关系. 字典(dict)是Python中唯一的映射类型,它是存储了一个个 键值对(由 键 映射到 值 ...

  6. Python基础(5)--字典

    字典由多个键及与其对应的值构成的对组成(把键值对成为项),每个键和它的值之间用冒号(:)隔开,项之间用逗号(,)隔开,而整个字典由一对大括号括起来.空字典由两个大括号组成:{} 本文地址:http:/ ...

  7. Python基础:1.数据类型(字典)

    提示:python版本:2.7,windows系统 1.字典(Dictionary) 由Key-Value组成,一个Key只能对应一个Value >>> colors = {'red ...

  8. Python基础之元组和字典

    一.元组: 1.定义: 内存图: 2.基本操作 3.元组作用: 4.元组基础知识代码 # . 创建空元组 t01 = () t02 = tuple() # . 创建具有默认值的元组 t01 = (,, ...

  9. Python基础(dict 和 set) 字典和set

    dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度. 举个例子,假设要根据同学的名字 ...

随机推荐

  1. SSH之Hibernate总结篇

    Hibernate hibernate 简介: hibernate是一个开源ORM(Object/Relationship Mipping)框架,它是对象关联关系映射的持久层框架,它对JDBC做了轻量 ...

  2. CodeBlocks(17.12) 代码调试基础方法&快捷方式

    转载:CodeBlocks(17.12) 代码调试基础方法&快捷方式: https://www.cnblogs.com/DCD112358/p/8998053.html

  3. 爬虫-通过本地IP地址从中国天气网爬取当前城市天气情况

    1.问题描述 ​ 最近在做一个pyqt登录校园网的小项目,想在窗口的状态栏加上当天的天气情况,用爬虫可以很好的解决我的问题. 2.解决思路 ​ 考虑到所处位置的不同,需要先获取本地城市地址,然后作为中 ...

  4. mysql索引与查询优化

    索引加锁 对于InnoDB来说,索引可以让查询锁住更少的行,从而可以在并发情况下拥有更佳表现. 下面演示一下查询锁与索引之间的关系. 前面使用的t_user_action_log表目前有一个id为主键 ...

  5. LightOJ 1349 Aladdin and the Optimal Invitation(中位数)

    题目链接:https://vjudge.net/contest/28079#problem/N 题目大意:给一个mxn的平面,有q个位置,每个位置坐标为(u,v)有w人,求一个点在平面内使得所有人都到 ...

  6. Oracle中和mysql中函数的区别

    oracle                  -->                 mysqlto_char(sysdate,'yyyy-mm-dd')-->date_format(s ...

  7. Shell的类型

    1.类Unix系统中有各种shell.如: /bin/bash /bin/csh /bin/ksh /bin/sh /bin/tcsh /bin/zsh 2.在/etc/shells文本文件中可以查看 ...

  8. .net core2.x 自动注入 Entity(实体对象到上下文)

    概要:有点老套,因为早在 .net frmework的时候(core还没出来),我们在使用 ef(4....6)的时候就已经这么用,这里我在搭建框架,所以随手写下,让后来人直接拿去用用. 1.使用前提 ...

  9. tensorflow 传入值-【老鱼学tensorflow】

    上个文章中讲述了tensorflow中如何定义变量以及如何读取变量的方式,本节主要讲述关于传入值. 变量主要用于在tensorflow系统中经常会被改变的值,而对于传入值,它只是当tensorflow ...

  10. 001 python基础实战

    报名了阿里大学的AI,一直没有学习,今天开始正式学习. 今天是第一节,Python的基础编程实战,里面包含两个示例. 一:任务实现文件的批量重命名. 1.创建一个目录 2.程序 #!/usr/bin/ ...