python编写字典库_Python中的字典及举例-阿里云开发者社区
字典
字典是python中的唯一的映射类型(哈希表)
字典对象是可变的,但是字典的键必须使用不可变对象,一个字典中可以使用不同类型的键值。
字典的方法
keys()
values()
items()
举例如下:
In [10]: dic = {}
In [11]: type(dic)
Out[11]: dict
In [12]:dic = {'a':1,1:123}
In [13]: dic
Out[13]: {1: 123, 'a': 1}
In [14]: dic = {'a':1,1:123,('a','b'):'hello'}
In [15]: dic = {'a':1,1:123,('a','b'):'hello',[1]:1}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in ()
----> 1 dic = {'a':1,1:123,('a','b'):'hello',[1]:1}
TypeError: unhashable type: 'list'
In [16]:len(dic)
Out[16]: 3
In [17]: dic.keys()
Out[17]: ['a', 1, ('a', 'b')]
In [18]:dic.values()
Out[18]: [1, 123, 'hello']
In [19]: dic.get('a')
Out[19]: 1
In [20]: dic
Out[20]: {1: 123, 'a': 1, ('a', 'b'): 'hello'}
In [21]: dic[1]
Out[21]: 123
更改字典内value:
In [22]:dic['a'] = 2
In [23]: dic
Out[23]: {1: 123, 'a': 2, ('a', 'b'): 'hello'}
查看是不是在字典里
In [28]:'b' in dic
Out[28]: False
In [29]:'a' in dic
Out[29]: True
In [30]: dic.has_key('a')
Out[30]: True
In [31]: dic.has_key('b')
Out[31]: False
变为列表:
In [32]:dic.items()
Out[32]: [('a', 2), (1, 123), (('a', 'b'), 'hello')]
In [33]: dic
Out[33]: {1: 123, 'a': 2, ('a', 'b'): 'hello'}
复制字典:
In [34]: dic1 = dic.copy()
In [35]: dic1
Out[35]: {1: 123, 'a': 2, ('a', 'b'): 'hello'}
In [36]: dic
Out[36]: {1: 123, 'a': 2, ('a', 'b'): 'hello'}
删除字典内容:
In [37]: dic.pop(1)
Out[37]: 123
In [38]: dic
Out[38]: {'a': 2, ('a', 'b'): 'hello'}
In [39]: dic.pop(2)
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
in ()
----> 1 dic.pop(2)
KeyError: 2
In [40]:
更新字典,两个字典更新为一个:
In [40]: dic1 = {1:1,2:2}
In [41]: dic.update(dic1)
In [42]: dic1
Out[42]: {1: 1, 2: 2}
In [43]: dic
Out[43]: {1: 1, 2: 2, 'a': 2, ('a', 'b'): 'hello'}
创建字典:
dic = {}
dic = dict()
help(dict)
dict((['a',1],['b',2]))
dict(a=1,b=2)
fromkeys(),字典元素有相同的值时,默认为None.
ddict = {}.formkeys(('x','y'),100)
dic.fromkeys(range(100),100)
In [45]: dic.fromkeys('abc')
Out[45]: {'a': None, 'b': None, 'c': None}
In [42]: dic = {}
In [43]: dic
Out[43]: {}
In [44]: dict()
Out[44]: {}
In [45]: dict(x=10,y=100)
Out[45]: {'x': 10, 'y': 100}
In [46]: dict([('a',10),('b',20)])
Out[46]: {'a': 10, 'b': 20}
访问字典:
In [10]: dic={1:1,2:3,3:5}
In [11]: dic
Out[11]: {1: 1, 2: 3, 3: 5}
In [12]: dic[2]
Out[12]: 3
In [13]: dic.items()
Out[13]: [(1, 1), (2, 3), (3, 5)]
for循环访问:
In [15]: for i in dic:
....: print i,dic[i]
....:
1 1
2 3
3 5
In [18]:for i in dic:
....: print "%s,%s" % (i,dic[i])
....:
1,1
2,3
3,5
In [19]: dic
Out[19]: {1: 1, 2: 3, 3: 5}
In [19]: dic
Out[19]: {1: 1, 2: 3, 3: 5}
In [21]:for k,v in dic.items():print k,v
1 1
2 3
3 5
字典练习
写出脚本,根据提示输入内容,并输入到字典中。
1种:
[root@localhost python]# cat dict.py
#!/usr/bin/python
#Author is fengXiaQing
#date 2017.12.22
info = {}
name = raw_input("Please input name:")
age = raw_input("Please input age:")
gender = raw_input("Please input (M/F):")
info['name'] = name
info['age'] = age
info['gender'] = gender
print info
[root@localhost python]#
[root@localhost python]# python dict.py
Please input name:fxq
Please input age:20
Please input (M/F):M
{'gender': 'M', 'age': '20', 'name': 'fxq'}
[root@localhost python]#
2.种
#!/usr/bin/python
#Author is fengXiaQing
#date 2017.12.22
info = {}
name = raw_input("Please input name:")
age = raw_input("Please input age:")
gender = raw_input("Please input (M/F):")
info['name'] = name
info['age'] = age
info['gender'] = gender
print info.items()
[root@localhost python]# python dict.py
Please input name:fxq
Please input age:22
Please input (M/F):M
[('gender', 'M'), ('age', '22'), ('name', 'fxq')]
[root@localhost python]#
3.种
#!/usr/bin/python
#Author is fengXiaQing
#date 2017.12.22
info = {}
name = raw_input("Please input name:")
age = raw_input("Please input age:")
gender = raw_input("Please input (M/F):")
info['name'] = name
info['age'] = age
info['gender'] = gender
for i in info.items():
print i
print "main end"
[root@localhost python]# python dict.py
Please input name:fxq
Please input age:22
Please input (M/F):M
('gender', 'M')
('age', '22')
('name', 'fxq')
main end
[root@localhost python]#
4.种
#!/usr/bin/python
#Author is fengXiaQing
#date 2017.12.22
info = {}
name = raw_input("Please input name:")
age = raw_input("Please input age:")
gender = raw_input("Please input (M/F):")
info['name'] = name
info['age'] = age
info['gender'] = gender
for k,v in info.items():
print k,v
print "main end"
[root@localhost python]# python dict.py
Please input name:fxq
Please input age:22
Please input (M/F):M
gender M
age 22
name fxq
main end
[root@localhost python]#
5.种
#!/usr/bin/python
#Author is fengXiaQing
#date 2017.12.22
info = {}
name = raw_input("Please input name:")
age = raw_input("Please input age:")
gender = raw_input("Please input (M/F):")
info['name'] = name
info['age'] = age
info['gender'] = gender
for k,v in info.items():
print "%s:%s" % (k,v)
print "main end"
[root@localhost python]# python dict.py
Please input name:fxq
Please input age:22
Please input (M/F):M
gender:M
age:22
name:fxq
main end
[root@localhost python]#
6.种
#!/usr/bin/python
#Author is fengXiaQing
#date 2017.12.22
info = {}
name = raw_input("Please input name:")
age = raw_input("Please input age:")
gender = raw_input("Please input (M/F):")
info['name'] = name
info['age'] = age
info['gender'] = gender
for k,v in info.items():
print "%s" % k
print "main end"
[root@localhost python]# python dict.py
Please input name:fxq
Please input age:22
Please input (M/F):M
gender
age
name
main end
[root@localhost python]#
练习:
1. 现有一个字典dict1 保存的是小写字母a-z对应的ASCII码
dict1 = {'a': 97, 'c': 99, 'b': 98, 'e': 101, 'd': 100, 'g': 103, 'f': 102, 'i': 105, 'h': 104, 'k': 107, 'j': 106, 'm': 109, 'l': 108, 'o': 96, 'n': 110, 'q': 113, 'p': 112, 's': 115, 'r': 114, 'u': 117, 't': 116, 'w': 119, 'v': 118, 'y': 121, 'x': 120, 'z': 122}
1) 将该字典按照ASCII码的值排序
print sorted(dict1.iteritems(), key=lambda d:d[1], reverse=False)
2) 有一个字母的ASCII错了,修改为正确的值,并重新排序
dict1['o']=111
print sorted(dict1.iteritems(), key=lambda d:d[1], reverse=False)
2. 用最简洁的代码,自己生成一个大写字母 A-Z 及其对应的ASCII码值的字典dict2(使用dict,zip,range方法)
dict2 = dict(zip(string.uppercase,range(65,92)))
print dict2
3. 将dict2与第一题排序后的dict1合并成一个dict3
dict3 = dict(dict1, **dict2)
# dict3 = dict(dict1, **dict2)等同于下面的两行代码
# dict3 = dict1.copy()
# dict3.update(dict2)
print dict3
本文转自 枫叶云 51CTO博客,原文链接:http://blog.51cto.com/fengyunshan911/2053754
python编写字典库_Python中的字典及举例-阿里云开发者社区相关推荐
- python调用 matlab库_python调用matlab的搜索结果-阿里云开发者社区
2018python技术问答集锦,希望能给喜欢python的同学一些帮助 小编发现问答专区中有很多人在问关于python的问题,小编把这些问题汇总一下,希望能给喜欢python的大家一些启示和帮助 本 ...
- python中右对齐_python中如何右对齐-问答-阿里云开发者社区-阿里云
例如,有一个字典如下: dic = { "name": "botoo", "url": "http://www.123.com&q ...
- python键盘怎么输入双引号_python中怎么输入引号
-问答-阿里云开发者社区-阿里云...
Python中的引号可分为单引号.双引号和三引号. 在Python中我们都知道单引号和双引号都可以用来表示一个字符串,比如 str1 = 'python' str2 = "python&qu ...
- python中如何输出中文_python中怎么输出中文-问答-阿里云开发者社区-阿里云
方法一: 用encode和decode 如: ? 1 2 3 4 5 6 7 8 9 10 11 import os.path import xlrd,sys Filename='/home/tom/ ...
- python 黑客工具开发_python黑客软件的搜索结果-阿里云开发者社区
带你读<Python科学计算(原书第2版)>之一:导论 计算机科学丛书点击查看第二章点击查看第三章Python科学计算(原书第2版)Python for Scientists, Secon ...
- python import from区别_python import 与 from .... import ...区别-阿里云开发者社区
在python用import或者from...import来导入相应的模块. 模块其实就一些函数和类的集合文件,它能实现一些相应的功能,当我们需要使用这些功能的时候, 直接把相应的模块导入到我们的程序 ...
- python安装gz文件_python tar.gz怎么安装-问答-阿里云开发者社区-阿里云
Windows环境: 安装whl包:pip install wheel -> pip install **.whl 下载whl文件 MySQL_python-1.2.5-cp27-none-wi ...
- python强大的模块_python之强大的日志模块-阿里云开发者社区
1.简单的将日志打印到屏幕 import logging logging.debug('This is debug message') logging.info('This is info messa ...
- python类的属性和对象属性_python 类属性、对象属性-阿里云开发者社区
类的普通属性: dir(Myclass), 返回一个key列表: Myclass.__dir__,返回一个字典: 1.类的数据属性: 2.类的方法: 类的特殊属性: 1.Myclass.__name_ ...
最新文章
- windbg 如何再内核模式调试用户空间的程序
- 阿里云ECS使用cloudfs4oss挂载OSS
- Linux命令 查看文件中指定行号的内容
- Java动态代理与反射详解
- 人工智能是互联网下一轮变革的核心
- 【原创】在C#中调用其它程序
- mongodb启动不能锁定_使用MongoDB进行乐观锁定重试
- 如何通过输入域名直接访问项目地址
- pytest结合allure-pytest插件生成allure测试报告
- 171021 逆向-Xp0intCTF(re300)
- 【016】基于51单片机的pwm加速减速步进电机Proteus仿真设计与实物设计
- 南柯服务器压力,从纳兰性德《木兰花》中看网络暴力和舆论压力带来的抑郁现象...
- 1台电脑可以上网,通过网络共享,让另外一台电脑也可以上网
- unity3dwebgl building之后没有反应_晚会是在考验明星临场反应吗?王源开场无伴奏阿云嘎差点原地跳舞...
- 《Activiti 深入BPM工作流 》--- 数据库表的命名规则是什么?
- 人工智能(python)开发 —— python 简要
- 云扩科技与帆软软件达成战略合作,携手共建RPA+BI新生态
- M5310-A通过MQTT连接阿里云平台教程
- 【Linux】权限讲解
- php数组及解析,PHP基本知识(数组解析)