Python之路,第八篇:Python入门与基础8

python3    字典(dict)

           概念:1 ,字典是一种可变的容器,可以存储任意类型的数据;  

                      2, 字典中的每个数据都是用“键”(key)进行索引,而不像序列可以用下标进行索引;

                      3, 字典中的数据没有先后关系,字典的存储是无序的;

                      4, 字符的数据是以键(key)-值(value)

                      5,字典的表示方式以{} 括起来,以冒号(:)分隔键值对, 各键值对之间用逗号隔开;

                     6, 字典的键不能重复,值可以重复;

           创建空字典的方法:

                  d = {}    # 空字典

                  d = dict() #空字典(迭代)

           创建非空字典的方法:

                    d = {‘a’:1 , 'b':2 }

                    d = {'name': None , 'age':18 }

            字典的值(value)可以为任意类型:

                   字典的值可以是布尔值,数据, 字符串, None,列表, 元组,字典,以及集合,函数,类对象等所有类型

 1 >>> 
 2 >>> {'a':123}
 3 {'a': 123}
 4 >>> {'a':"abc"}
 5 {'a': 'abc'}
 6 >>> {'a':True}
 7 {'a': True}
 8 >>> {'a':None}
 9 {'a': None}
10 >>> {'a':(1,2,3)}
11 {'a': (1, 2, 3)}
12 >>> {'a':[1,2,3]}
13 {'a': [1, 2, 3]}
14 >>> {'a':{"aa":1}}
15 {'a': {'aa': 1}}
16 >>> 
View Code

 

           字典的键(key) 必须为不可变类型的值

                    不可变的类型: bool  、int 、 float 、 complex 、 str 、 tuple 、frozenset  (包括:None)

           不能充当键的类型有:

                   列表list,字典dict,集合set

                    例子: {}

 1 >>> {"a":"a"}
 2 {'a': 'a'}
 3 >>> {100:"100"}
 4 {100: '100'}
 5 >>> {True:"True"}
 6 {True: 'True'}
 7 >>> {None:"abc"}
 8 {None: 'abc'}
 9 >>> {(1911,1,1):"aaa"}
10 {(1911, 1, 1): 'aaa'}
11 >>> 
View Code

           练习:

回文

 1 #!/usr/bin/python
 2 
 3 s = input("Please enter:")
 4 n = len(s) // 2
 5 for x in range(0, n + 1):
 6     if s[x] != s[ -( x+1)]:
 7         print("不是回文")
 8         break
 9 else:
10     print("是回文")
11 >>> ================================ RESTART ================================
12 >>> 
13 Please enter:123321
14 是回文
15 >>> ================================ RESTART ================================
16 >>> 
17 Please enter:abccba
18 是回文
19 >>> ================================ RESTART ================================
20 >>> 
21 Please enter:21352656121
22 不是回文
23 >>> ================================ RESTART ================================
24 >>> 
25 Please enter:fargserwaqrg
26 不是回文
27 >>> 
View Code
 1 #!/usr/bin/python
 2 
 3 s = input("Please enter:")
 4 l = list(s) #正序列表
 5 l2 = list(reversed(s)) ##反序列表
 6 if l == l2:
 7     print("是回文")
 8 else:
 9     print("不是回文")
10 >>> ================================ RESTART ================================
11 >>> 
12 Please enter:asddsa
13 是回文
14 >>>     
View Code
1 #!/usr/bin/python
2 
3 s = input("Please enter:")
4 print(s)
5 print(s[::-1])
6 if s == s[::-1]:
7     print("是回文")
8 else:
9     print("不是回文")
View Code

 

 数字出现次数

 1 #!/usr/bin/python
 2 
 3 exist = [] # 已访问过的列表
 4 s = input("请输入一串数字:")
 5 for x in s:
 6     if x not in exist:
 7         print(x, '出现', s.count(x), '')
 8         exist.append(x)
 9 
10 #for x in s:
11 #    if x in exist:
12 #        pass
13 #    else:
14 #        print(x, '出现', s.count(x), '次')
15 #        exist.append(x)
16 >>> ================================ RESTART ================================
17 >>> 
18 请输入一串数字:7324525901243
19 7 出现 120 3 出现 221 2 出现 322 4 出现 223 5 出现 224 9 出现 125 0 出现 126 1 出现 127 >>> 
View Code

 

 

            字典符访问:

                   用方括号访问字典内的成员,字典[‘’键‘’] ;

1 >>> d = {'a':1 , 'b':2}
2 >>> d['a']
3 1
4 >>> d['b']
5 2
6 >>> 
View Code      

              添加或修改字典的键的值:

                      字典[ "键" ] = 值

                      如果,键存在,修改键绑定的值; 如果键不存在,创建键并帮定值;

1 >>> d1 = {}    #创建空字典
2 >>> type(d1)
3 <class 'dict'>
4 >>> d1['name'] = 'xiaoming'  #添加键值对
5 >>> d1['age'] = 18              ##添加键值对
6 >>> d1['age'] = 19               #修改键的值    
7 >>> 
View Code

 

             删除字典元素  del

                      del     字典【键】

1 >>> d1
2 {'age': 19, 'name': 'xiaoming'}
3 >>> del d1['age']
4 >>> d1
5 {'name': 'xiaoming'}
6 >>
View Code

 

            获取字典元素个数的函数:

                      len(dict) 返回字典元素(键值对)个数;

             字典的成员资格判断in   、not in 运算符;

                       用in  、not in 来判断一个键是否存在于字典中,如果存在则返回True, 如果不存在则返回False;

1 >>> d1
2 {'age': 16, 'name': 'xiaoming'}
3 >>> 
4 >>> 
5 >>> 'name' in d1
6 True
7 >>> 16 in d1
8 False
9 >>> 
View Code

 

            字典的生成函数:

                 dict()    生成一个函数,等同于{ }

                dict(iterable)   用可迭代对象初始化字典

                dict(**kwargv ) 关键字参数形式生成一个字典

           例子: d  = dict()

                      >>> d = dict([('name','xiaoming'),('age', 18)])      #{'age': 18, 'name': 'xiaoming'}    返回字典

                      d = dict(name="xiaoli", age=19)      #{'age': 19, 'name': 'xiaoli'}

                      d = {}   # name = "zhangsan"      {'name' : name}     {'name': 'zhangsan'}

 

               字典的方法:

D     代表字典对象

D.clear()                     清空字典

D.pop(key)                 移除键,同时返回此键所对应的值

D.copy()                     返回字典D的副本,只复制一层,(浅拷贝)

D.update(D2)             将字典D2合并到字典D中,如果键相同则值取D2的值作为新值;

D.get(key , default)        返回键key所对应的值,如果没有此键则返回default

D.keys()                         返回可迭代的dict_keys 集合对象

D.values()                      返回可迭代的dict_values 值对象

D.items()                        返回可迭代的dict_iterm对象

 1 >>> help(d.get)
 2 Help on built-in function get:
 3 
 4 get(...) method of builtins.dict instance
 5     D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
 6 
 7 >>> d
 8 {'age': 19, 'name': 'xiaoli'}
 9 >>> 
10 >>> 
11 >>> d.clear
12 <built-in method clear of dict object at 0x000000000372B948>
13 >>> d
14 {'age': 19, 'name': 'xiaoli'}
15 >>> d.clear()
16 >>> d
17 {}
18 >>> d={'age': 19, 'name': 'xiaoli'}
19 >>> d
20 {'age': 19, 'name': 'xiaoli'}
21 >>> d.pop('name')
22 'xiaoli'
23 >>> d1
24 {'age': 16, 'name': 'xiaoming'}
25 >>> del d1
26 >>> d2
27 Traceback (most recent call last):
28   File "<pyshell#47>", line 1, in <module>
29     d2
30 NameError: name 'd2' is not defined
31 >>> d1
32 Traceback (most recent call last):
33   File "<pyshell#48>", line 1, in <module>
34     d1
35 NameError: name 'd1' is not defined
36 >>> d.copy(d1)
37 Traceback (most recent call last):
38   File "<pyshell#49>", line 1, in <module>
39     d.copy(d1)
40 NameError: name 'd1' is not defined
41 >>> d1 = d.copy()
42 >>> d1
43 {'age': 19}
44 >>> d
45 {'age': 19}
46 >>> d.get('name', "没找到")
47 '没找到'
48 >>> d
49 {'age': 19}
50 >>> d2 = {'aa':1,'bb':2}
51 >>> d.update(d2)
52 >>> d
53 {'age': 19, 'bb': 2, 'aa': 1}
54 >>> d2
55 {'bb': 2, 'aa': 1}
56 >>> d.keys()
57 dict_keys(['age', 'bb', 'aa'])
58 >>> d.values()
59 dict_values([19, 2, 1])
60 >>> d.items()
61 dict_items([('age', 19), ('bb', 2), ('aa', 1)])
62 >>> 
63 >>> d.items()
64 dict_items([('age', 19), ('bb', 2), ('aa', 1)])
65 >>> for k in d.keys():
66     print(k)
67 
68     
69 age
70 bb
71 aa
72 >>> for k,v in d.items():
73     print(k,v)
74 
75     
76 age 19
77 bb 2
78 aa 1
79 >>> for v in d.values():
80     print(v)
81 
82     
83 19
84 2
85 1
86 >>> 
View Code

 

 

            字典推导式:

                   语法:   { 键表达式 : 值表达式  for  变量  in 可迭代对象   (if 条件表达式) }

                   字典推导式可以嵌套的

1 >>> name
2 ['xiaoming', 'xiaoli', 'xiaogang', 'zhangsan']
3 >>> numbers = [1001, 1002, 1003, 1004]
4 
5 >>> an = { numbers[i] : name[i] for i in range(4) if numbers[i] % 2 == 0}
6 >>> an
7 {1002: 'xiaoli', 1004: 'zhangsan'}
8 >>> 
View Code

 

 

1 >>> list1 = ['a','b','c']
2 >>> list2 = [1,2,3]
3 >>> dict_a = { list1[i] : list2[i] for i in range(3)}
4 >>> dict_a
5 {'a': 1, 'c': 3, 'b': 2}
6 >>> 
View Code

 

           字典和列表的比较:

                  in 、 not in

                  列表的in 操作通常要每个都进行比较;

                  字典的in 操作不需要比较;

          字典的基本函数操作:

len(x)      返回字典的长度

max(x)     返回字典键的最大值

min(x)      返回字典键的最小值

sum(x)      返回字典中所有键的和

any(x)       真值测试,任意键为真,则返回True,否则为False

all(x)          真值测试,所有键为真,则返回True,否则为False   

例子

 

posted on 2018-05-02 22:17  微子天明  阅读(177)  评论(0编辑  收藏  举报

导航