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)

<ipython-input-15-4fc52e86cb96> in <module>()

----> 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)

<ipython-input-39-9f97239cddce> in <module>()

----> 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种:

[[email protected] 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

[[email protected] python]#

[[email protected] python]# python dict.py

Please input name:fxq

Please input age:20

Please input (M/F):M

{'gender': 'M', 'age': '20', 'name': 'fxq'}

[[email protected] 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()

[[email protected] python]# python dict.py

Please input name:fxq

Please input age:22

Please input (M/F):M

[('gender', 'M'), ('age', '22'), ('name', 'fxq')]

[[email protected] 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"

[[email protected] 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

[[email protected] 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"

[[email protected] 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

[[email protected] 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"

[[email protected] 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

[[email protected] 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"

[[email protected] python]# python dict.py

Please input name:fxq

Please input age:22

Please input (M/F):M

gender

age

name

main end

[[email protected] 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

时间: 2024-11-09 05:39:46

Python中的字典及举例的相关文章

Python中的字典详解

Python中的字典是python的一种数据结构,它的本质是key和value以及其对应关系的一种集合,一个key可以对应一个多个value.合理的使用字典能给我们编程带来很大的方便. -----python中的数据类型 -----python中的字符串操作 python3.0以上,print函数应为print(),不存在dict.iteritems()这个函数. 在python中写中文注释会报错,这时只要在头部加上# coding=gbk即可 #字典的添加.删除.修改操作dict = {"a&

Python中的字典

字段是Python是字典中唯一的键-值类型,是Python中非常重要的数据结构,因其用哈希的方式存储数据,其复杂度为O(1),速度非常快.下面列出字典的常用的用途. [字典中常见方法列表] #方法 #描述 ------------------------------------------------------------------------------------------------- D.clear() #移除D中的所有项 D.copy() #返回D的副本 D.fromkeys(s

Python中的字典排序

Python中比较常用的排序有两个函数, 一.定义 (1)一个是List数据结构中的sort >>> help(list.sort)Help on method_descriptor: sort(...) L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; cmp(x, y) -> -1, 0, 1 The sort() method takes optional arguments for co

python中的字典内置方法小结

#!/usr/local/bin/python3 # -*- coding:utf-8 -*- #key-value #dict 无序,无下标,不需要下标,因为有key stu={ 'stu001':"zhang yu", 'stu002':"ma hong yan", 'stu003':"zhang guo bin", 'stu004':"sha chun hua" } ''' -----------------------

python中的字典(dict)

首先说一下字典是什么: 字典是一种容器模型,可以通过搜索Key键获得其对应值得数据结构,字典可以储存任何类型的对象.字典里面的每个Key和value之间用冒号隔开.其键可以是字符串.数字.元组,字典是Python中唯一内置的映射类型. 注:键最好不要用浮点 字典所包含的方法如下表: 序号 方法 描述 1 clear(self) 删除字典里面的所有元素 2 copy(self) 返回值类型为字典,浅copy ,俗称赋值 3 fromkey(*args,**kwargs) 创建一个新字典,以序列se

13.python中的字典

字典其实和之前的元祖和列表功能相似,都是用来储存一系列对象的.也就是一种可变容器,或者是我所比喻的革新派的菜单. 但也不是完全相同,我在之前曾经将字典称为特殊的'序列',是字典拥有序列的部分特性,但是又不符合序列的定义. 首先我们来看下字典是如何创建的: a = {'a':1,'b':2,'c':2} b = {} c = dict(a=1) print a print b print c 我们可以使用{} 或者dict() 来创建一个字典对象. 但字典里面写的是什么?下面我来分析一下. 首先,

python中的字典应用实例

字典中的键使用时必须满足一下两个条件: 1.每个键只能对应一个项,也就是说,一键对应多个值时不允许的(列表.元组和其他字典的容器对象除外).当有键发生冲突时(即字典键重复赋值),取最后的赋值. >>> myuniversity_dict = {'name':'yuanyuan', 'age':18, 'age':19, 'age':20, 'schoolname':Chengdu, 'schoolname':Xinxiang} Traceback (most recent call la

Python中的字典方法

1.clear clear方法清除字典中的所有项.无返回值 d = {'age' : 42, 'name':'Gumby'} d.clear()>>> d{} 2.copy copy方法返回一个具有相同键-值对的新字典 d = {'age' : 42, 'name' : 'Gumby'} b = d.copy()>>> b{'age' : 42, 'name' : 'Gumby'} 3.fromkeys fromkeys方法使用键值组成的序列创建新的字典,每个键值默认对

Python中的循环退出举例及while循环举例

循环退出 for循环: for else for 循环如果正常结束,都会执行else语句. 脚本1: #!/usr/bin/env python for i in xrange(10): print i else: print "main end" 结果: [[email protected] 20171227]# python exit.py 0 1 2 3 4 5 6 7 8 9 main end [[email protected] 20171227]# 脚本2: #!/usr/