python之字典的书写

python之字典

1、字典的说明
定义:字典是另一种可变容器模型,且可存储任意类型对象,他是由key:value键值对组成的。

 

2、字典的代码
2.1、字典的定义

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})

个人喜欢第1,2种,检查这些是否相等

>>> a == b == c == d == e
True

2.2、字典的修改和删除

>>> d = {'a': 12, 'c': 13, 'b': 14}

#字典的修改
>>> d['a'] = 1
>>> d
{'a': 1, 'c': 13, 'b': 14}

#删除字典
>>>del d

 

2.3、字典的遍历

先定义一个字典d

>>> d = {'a':12, 'c':13, 'b':14}
>>> d #直接输出
{'a': 12, 'c': 13, 'b': 14}
>>> d['a'] #输出某个值
12

2.3.1 输出字典d中的key值

直接输出

1 >>> list(d.keys())
2 ['a', 'c', 'b']

用函数sorted()整理后输出

1 >>> sorted(d.keys())
2 ['a', 'b', 'c']

2.3.2 key:value均遍历输出

>>> for key in d:
...     print(key,':', d[key]) #d[key] 就是其value值


#整理其值后遍历
>>> for key in sorted(d):  
...          print(key, ':', d[key])
#使用 enumerate() 函数 >>> for i, v in enumerate(d): ... print(i,v,':', d[v]) ... 0 a : 12 1 c : 13 2 b : 14 #使用items()方法遍历 >>> for key, value in d.items(): ... print(key,':', value) ... a : 12 c : 13 b : 14 #将字典a和d打包遍历输出 >>> a = dict(one=1, two=2, three=3) >>> for i, j in zip(a, d): ... print(i, ':', a[i], j, ':', d[j]) ... one : 1 a : 12 two : 2 c : 13 three : 3 b : 14

2.4 字典在函数中的传递

2.4.1 传递一个字典

1 >>> def dict_test(d):
2 ...     for key in sorted(d):
3 ...         print(key, ':', d[key])
4 ...
5 >>> dict_test(d)
6 a : 12
7 b : 14
8 c : 13

 

2.4.2 一个一个字典元素传递遍历

 1 >>> def dict_test_more(**d):
 2 ...     for key in sorted(d):
 3 ...         print(key, ':', d[key])
 4 ...
 5 
 6 >>> dict_test_more(**d)
 7 a : 12
 8 b : 14
 9 c : 13
10 
11 
12 >>> dict_test_more(one=1, two=2, three=3)
13 one : 1
14 three : 3
15 two : 2

2.4.3 多个字典传入(原谅我投机取巧了)

1 >>> def dict_more(*d):
2 ...     print(*d)
3 ...
4 >>> dict_more(a,d)
5 {'one': 1, 'two': 2, 'three': 3} {'a': 1, 'c': 13, 'b': 14}

 

posted @ 2019-03-05 16:06  科技之夜  阅读(1351)  评论(0编辑  收藏  举报