习题40,字典的操作

things = ['a', 'b', 'c', 'd']#列表
print(things[1])#打印列表索引是1的元素b
things[1] = '2'#修改列表第2个元素改为2
print(things[1])#再次打印列表第2个元素
print(things)#打印出所有列表元素

D:\软件\py36\python.exe E:\python\day15\31\xiti39.py 
b
2
['a', '2', 'c', 'd']

进程已结束,退出代码0

stuff = {'name': 'Zed', 'age': 36, 'height': 6*12+2}#字典stuff
print(stuff['name'])#打印字典元素name
print(stuff['age'])#打印字典元素年龄
print(stuff['height'])#打印字典元素体重
stuff['city'] = "shanxi"#添加字典元素城市
print(stuff['city'])#打印字典元素城市

字典里通过键值来添加元素,删除元素

D:\软件\py36\python.exe E:\python\day15\31\xiti39.py 
Zed
36
74
shanxi

进程已结束,退出代码0
stuff = {'name': 'Zed', 'age': 36, 'height': 6*12+2}#字典stuff
print(stuff['name'])#打印字典元素name
print(stuff['age'])#打印字典元素年龄
print(stuff['height'])#打印字典元素体重
stuff['city'] = "shanxi"#添加字典键值城市元素shanxi
print(stuff['city'])#打印字典元素城市,通过打印键值
stuff[1] = "Wow"
stuff[2] = 'Neato'
print(stuff[1])#打印键值是1的元素
print(stuff[2])#打印键值是2的元素
print(stuff)#打印整个字典
del stuff['city']#根据键值city删除元素
del stuff[1]#根据键值1来删除元素
print(stuff)#打印整个字典

输出结果:

D:\软件\py36\python.exe E:\python\day15\31\xiti39.py 
Zed
36
74
shanxi
Wow
Neato
{'name': 'Zed', 'age': 36, 'height': 74, 'city': 'shanxi', 1: 'Wow', 2: 'Neato'}
{'name': 'Zed', 'age': 36, 'height': 74, 2: 'Neato'}

进程已结束,退出代码0

# =============================================================================
# create a mapping of state to abbreviation#创建一个映射
# =============================================================================
states = {#州
    "Oregon": "OR",#俄勒冈州
    "Florida": "FL",#佛我利达
    "Carlifornia": "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 more cities#添加更多的 城市
# =============================================================================
cities["NY"] = "New York"#纽约
cities["OR"] = "Portland"#波特兰

# =============================================================================
# print out some cities#打印出一些城市
# =============================================================================
print("-" * 10)#打印10个“-”连接在一起
print("NY state has: ", cities["NY"])
print("OR state has: ", cities["OR"])

# =============================================================================
# print some states#打印一些状态
# =============================================================================
print("-" * 10)#打印10个“-”连接在一起
print("Michigan's abbreviation is: ", states["Michigan"])#密歇根的缩写是
print("Florida's abbreviation is: ", states["Florida"])#打印出一些城市

# =============================================================================
# do it by using the state then cities dict#是通过使用州和城市的词典
# =============================================================================
print("-" * 10)#打印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()):  # items()函数是个新东西
    print(f"{state} is abbreviated {abbrev}")#打印出每个州的缩写

# =============================================================================
# print every city in state#打印每个州的城市
# =============================================================================
print("-" * 10)#打印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()):
# for state, abbrev in states.items(): #这个代码也可以运行成功
for (state, abbrev) in states.items():  #打印出州和缩写 这个代码也可以运行成功
    print(f"{state} state is abbreviated {abbrev}")#打印出州和缩写
    print(f"and has city {cities[abbrev]}")

# =============================================================================
# states.items()
# Out[6]: dict_items([('Oregon', 'OR'), ('Florida', 'FL'), ('Carlifornia', 'CA'), ('New York', 'NY'), ('Michigan', 'MI')])
# 看到items()函数给出键值对组成的元祖不可动,然后再组成一个list
# 这里list函数
# 以上三行代码都可以,加括号表示tuple类型,list()函数转换成列表
#
# =============================================================================
print("-" * 10)#打印10个“-”连接在一起
# =============================================================================
# safely get a abbreviation by state that might not be there#写出每个城市的缩写
# =============================================================================
state = states.get("Texas")#德克萨斯州

if not state:
    print("Sorry, no Texas.")#对不起,,找不到德克萨斯州

# =============================================================================
# get a city with a default value 不存在给出默认值
# Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值
# =============================================================================
city = cities.get("TX", "Does Not Exist")#查询德克萨斯州
print(f"The city for the state 'TX' is: {city}")#州缩写TX 查询不到德克萨斯州
# =============================================================================
# 语法是 dict.get(key, default=None)
#
# key -- 字典中要查找的键。
#
# default -- 如果指定键的值不存在时,返回该默认值
#
# 这里 key 就是 Texas,意思就是要查找它,然后找不到就返回None
# =============================================================================

运行结果:

D:\软件\py36\python.exe E:\python\day15\31\习题339.py 
----------
NY state has:  New York  纽约州有:纽约州 
OR state has:  Portland  OR州:波特兰
----------
Michigan's abbreviation is:  MI   密歇根的缩写是MI  
Florida's abbreviation is:  FL    佛里达州缩写是FL
----------
Michigan has: Detroit    密歇根州有:底特律
Florida has:  Jacksonville    佛罗里达州有:杰克逊维尔
----------
Oregon is abbreviated OR    俄勒冈州缩写为OR
Florida is abbreviated FL    佛罗里达缩写为F
Carlifornia is abbreviated CA    加州缩写为CA
New York is abbreviated NY    纽约缩写为NY
Michigan is abbreviated MI    密歇根缩写为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 state is abbreviated OR      俄勒冈州缩写为OR,拥有波特兰市 
and has city Portland
Florida state is abbreviated FL      佛罗里达州简称FL,有杰克逊维尔市
and has city Jacksonville
Carlifornia state is abbreviated CA    加利福尼亚州缩写为CA,有旧金山市
and has city San Francisco
New York state is abbreviated NY    纽约州简称NY,有纽约市New York
and has city New York
Michigan state is abbreviated MI    密歇根州缩写为MI,拥有底特律市
and has city Detroit
----------
Sorry, no Texas.    抱歉,德州不行
The city for the state 'TX' is: Does Not Exist 德州“TX”的城市是:不存在   

进程已结束,退出代码0

字典(Dictionary)
字典是另一种可变容器模型,且可存储任意类型对象。

字典是可变的

字典是包括在{}中,含有key(键):value(值)格式的键值对,且每个键值对之间用,分割的模型

格式如下所示:

d = {key1 : value1, key2 : value2 }

键一般是唯一的,值不需要唯一。

如果键重复,最后的一个键值对会替换前面的

值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。列表不行。

创建字典
方法一:花括号括住键值对

​ {‘键’:‘值’, … ,‘键’:‘值’ }

方法二:dict()函数

​ dict(键=值,键=值)

实例
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
1

dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6: 37 }
1
2
访问字典里的值
返回所有键

字典名. key()

返回所有值

字典名.value()

返回键值对的元组

字典名.items()

返回键对应的值

字典名.get()

把相应的键放入字典名称后的方括弧,如下实例:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
1
2
3
4
dict['Name']:  Zara
dict['Age']:  7
1
2
如果用字典里没有的键访问数据,会输出错误如下:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print "dict['Alice']: ", dict['Alice']
1
2
3
dict['Alice']: 
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print "dict['Alice']: ", dict['Alice']
KeyError: 'Alice'
1
2
3
4
5
修改字典
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对。如下实例:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

dict['Age'] = 8 # 更新
dict['School'] = "RUNOOB" # 添加


print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
1
2
3
4
5
6
7
8
dict['Age']:  8
dict['School']:  RUNOOB
1
2
删除字典元素
能删单一的元素也能清空字典,清空只需一项操作。

删除键对应的键值对

dict.pop() # 返回删除的键值对

del dict[‘键’]

删除字典

del dict

清空字典中的内容

dict.clear()

如下实例:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

del dict['Name']  # 删除键是'Name'的条目
dict.clear()      # 清空字典所有条目
del dict          # 删除字典

print "dict['Age']: ", dict['Age'] 
print "dict['School']: ", dict['School']
1
2
3
4
5
6
7
8
但这会引发一个异常,因为用del后字典不再存在:

dict['Age']:
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print "dict['Age']: ", dict['Age'] 
TypeError: 'type' object is unsubscriptable
1
2
3
4
5
注:del()方法后面也会讨论。

键的特性
字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。

两个重要的点需要记住:

不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住
键必须不可变,所以可以用数字,字符串或元组充当,用列表就不行
字典内置函数&方法
Python字典包含了以下内置函数:

序号    函数及描述
len(dict)    计算字典元素个数,即键的总数
str(dict)    输出字典,以可打印的字符串表示
type(variable)    返回输入的变量类型,如果变量是字典就返回字典类型
Python字典包含了以下内置方法:

序号    函数及描述
dict.clear()    删除字典内所有元素
dict.copy()    返回一个字典的浅复制
dict.fromkeys(seq[, val])    创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值
dict.get(key, default=None)    返回指定键的值,如果值不在字典中返回default值
key in dict    如果键在字典dict里返回true,否则返回false
dict .items()    以列表返回可遍历的(键, 值) 元组数组
dict.keys()    返回一个迭代器,可以使用 list() 来转换为列表
dict.setdefault(key, default=None)    和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
dict.update(dict2)    把字典dict2的键/值对更新到dict里
dict.values()    以列表返回字典中的所有值
pop(key[,default])    删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值
popitem()    返回并删除字典中的最后一对键和值
.items()方法
字典(Dictionary)

描述
Python 字典(Dictionary) items() 函数把字典中每对 key 和 value 组成一个元组,并把这些元组放在列表中返回

语法
dict.items()
1
参数
NA。
返回值
返回可遍历的(键, 值) 元组数组。

.get()方法
字典(Dictionary)

描述
Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。

语法
dict.get(key, default=None)
1
参数
key – 字典中要查找的键。
default – 如果指定键的值不存在时,返回该默认值。
返回值
返回指定键的值,如果值不在字典中返回默认值None。

实例
dict = {'Name': 'Runoob', 'Age': 27}

**print** "Value : %s" %  dict.get('Age')
**print** "Value : %s" %  dict.get('Sex', "Never")
1
2
3
4
Value : 27
Value : Never
1
2
dick. keys() 方法
描述
dick.keys() 方法返回一个可迭代对象,可以使用 list() 来转换为列表。

语法
dict.keys()
1
参数
NA。
返回值
返回一个迭代器。

实例
以下实例展示了 keys() 方法的使用方法:

>>> dict = {'Name': 'Runoob', 'Age': 7}
>>> dict.keys()
dict_keys(['Name', 'Age'])
>>> list(dict.keys())             # 转换为列表
['Name', 'Age']
>>> 
1
2
3
4
5
6
以上实例输出结果为:


————————————————
版权声明:本文为CSDN博主「weixin_45938096」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_45938096/article/details/106747609

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值