首页 技术 正文
技术 2022年11月11日
0 收藏 305 点赞 2,969 浏览 1627 个字

  Python中的字典与现实中字典类似,从字典中可以找到“”字:鱼类是体被骨鳞、以鳃呼吸、通过尾部和躯干部的摆动以及鳍的协调作用游泳和凭上下颌摄食的变温水生脊椎动物。类比到Python的字典中,把“鱼”这个字称为“键(key)”,把其对应的含义称为“值(value)”。

  字典是Python中唯一的映射类型,映射是数学上的一个术语,指两个元素集之间相互对应的关系。

  [Python]字典的简单用法

  字典的几种创建方法

 dict1=dict((('F',70),('i',105),('s',115),('h',104),('c',67)))
dict2=dict(F=70,I=105,S=115,H=104,C=67)
dict3=dict((('F',70),('I',105),('S',110)))

  字典的内置方法:

  1.fromkeys()

  fromkeys()方法用于创建并返回一个新的字典,有两个参数,第一个是字典的键,第二个是可选的值,若不输入则默认为None。

dict3={}
print(dict3.fromkeys((1,2,3)))
dict4={}
print(dict4.fromkeys((1,2,3),"Number"))

  输出结果则是:

  {1: None, 2: None, 3: None}
  {1: ‘Number’, 2: ‘Number’, 3: ‘Number’}

  2.keys(),values(),items()

  keys()用于返回字典中的键,values()用于返回字典中的所有的值,items()用于返回字典中所有的键值对应关系。

dict5={}
dict5=dict5.fromkeys(range(5),"")
print(dict5.keys())
print(dict5.values())
print(dict5.items())

  输出结果是:

  dict_keys([0, 1, 2, 3, 4])
  dict_values([‘1’, ‘1’, ‘1’, ‘1’, ‘1’])
  dict_items([(0, ‘1’), (1, ‘1’), (2, ‘1’), (3, ‘1’), (4, ‘1’)])

  3.get()

  如果直接访问不存在的字典项:

dict5={}
dict5=dict5.fromkeys(range(5),"")
print(dict5[5]);

  则会报错:

  Traceback (most recent call last):
     File “D:/python/test.py”, line 3, in <module>
    print(dict5[5]);
  KeyError: 5

  get()方法提供了更宽松的访问字典的方法,如果访问字典项不存在不会报错,而是返回一个None值:

dict5={}
dict5=dict5.fromkeys(range(5),"")
print(dict5.get(5));

  结果返回None。

  4.copy()  复制字典

a={1:"one",2:"two",3:"three"}
b=a.copy()
print(b,"")
a.clear()
print(b,"")

  

  5.pop()和popitem()

  pop()是给定键弹出对应值,而popitem是弹出一个项。

a={1:"one",2:"two",3:"three",4:"four"}
print(a.pop(2))
print(a)
print(a.popitem(),a.popitem())
print(a)

  结果:

  two
  {1: ‘one’, 3: ‘three’, 4: ‘four’}
  (4, ‘four’) (3, ‘three’)
  {1: ‘one’}

  

  6.update()

  用来更新字典。

pets={"米奇":"老鼠","汤姆":"猫","小白":"猪"}
print(pets)
pets.update(小白="狗")
print(pets)
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,105
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,582
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,429
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,836
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,919