python中字典(Dictionary)操作详解
Python 中的字典是Python中一个键值映射的数据结构
一,字典的基础操作
1.1 创建字典
Python有两种方法可以创建字典,第一种是使用花括号,另一种是使用内建 函数dict
>>> dict_A = {}
>>> dict_A = dict()
1.2 初始化字典
Python可以在创建字典的时候初始化字典
>>> dict_A = {"name" : \'cold\'}
>>> dict_A = dict(name = \'cold\') # 更优雅
很明显第二种方法更加的优雅和减少一些特殊字符的输入,但是有种情况第二种不能胜任
>>> key = \'name\'
>>> dict_A = { key :\'cold\'} # {\'name\':\'cold\'}
>>> dict_A = dict(key = \'cold\') # {\'key\': \'cold\'}
明显第二种方法就会引发一个不容易找到的bug
Python字典还有一种初始化方式,就是使用字典的fromkeys方法可以从列表中获取元素作为键并用None或fromkeys方法的第二个参数初始化
>>> dict_A = {}.fromkeys([\'name\', \'blog\'])
>>> dict_A
{\'blog\': None, \'name\': None}
>>> dict_A = dict().fromkeys([\'name\', \'blog\'])
>>> dict_A
{\'blog\': None, \'name\': None}
>>> dict_A = dict().fromkeys([\'name\', \'blog\'], \'linuxzen.com\')
>>> dict_A
{\'blog\': \'linuxzen.com\', \'name\': \'linuxzen.com\'}
1.3 优雅的获取键值
字典可以这样获取到键的值
>>> dict_A = {\'name\':\'cold\', \'blog\':\'linuxzen.com\'}
>>> dict_A[\'name\']
\'cold\'
但是如果获取不存在的键的值就会触发的一个KeyError异常,字典有一个get方法,可以使用字典get方法更加优雅的获取字典
>>> dict_A = dict(name= \'cold\', blog=\'www.linuxzen.com\')
>>> dict_A.get(\'name\')
\'cold\'
>>> dict_A.get(\'blogname\')
None
>>> dict_A.get(\'blogname\', \'linuxzen\')
\'linuxzen\'
我们看到使用get方法获取不存在的键值的时候不会触发异常,同时get方法接收两个参数,当不存在该键的时候就会返回第二个参数的值 我们可以看到使用get更加的优雅
1.4 更新/添加
Python 字典可以使用键作为索引来访问/更新/添加值
>>> dict_A = dict()
>>> dict_A[\'name\'] = \'cold\'
>>> dict_A[\'blog\'] = \'linuxzen.com\'
>>> dict_A
{\'blog\': \'linuxzen.com\', \'name\': \'cold\'}
>>> dict_A
{\'blog\': \'linuxzen.com\', \'name\': \'cold night\'}
同时Python字典的update方法也可以更新和添加字典
>>> dict_A = dict(name=\'cold\', blog=\'linuxzen.com\')
>>> dict_A.update({\'name\':\'cold night\', \'blogname\':\'linuxzen\'})
>>> dict_A
{\'blog\': \'linuxzen.com\', \'name\': \'cold night\', \'blogname\': \'linuxzen\'}
>>> dict_A.update(name=\'cold\', blog=\'www.linuxzen.com\') # 更优雅
>>> dict_A
{\'blog\': \'www.linuxzen.com\', \'name\': \'cold\', \'blogname\': \'linuxzen\'}
Python字典的update方法可以使用一个字典来更新字典,也可以使用参数传递类似dict函数一样的方式更新一个字典,上面代码中哦功能的第二个更加优雅,但是同样和dict函数类似,键是变量时也只取字面值
1.5 字典删除
可以调用Python内置关键字del来删除一个键值
>>> dict_A = dict(name=\'cold\', blog=\'linuxzen.com\')
>>> dict_A
{\'blog\': \'linuxzen.com\', \'name\': \'cold\'}
>>> del dict_A[\'name\']
>>> dict_A
{\'blog\': \'linuxzen.com\'}
同时也可以使用字典的pop方法来取出一个键值,并删除
>>> dict_A = dict(name=\'cold\', blog=\'linuxzen.com\')
>>> dict_A.pop(\'name\')
\'cold\'
>>> dict_A
{\'blog\': \'linuxzen.com\'}
1.6 获取key,value
获取所有key
>>> dict_A = dict(name=\'cold\', blog=\'linuxzen.com\')
>>> dict_A.keys()
[\'blog\', \'name\']
获取key,value并循环
>>> dict_A = dict(name=\'cold\', blog=\'linuxzen.com\')
>>> for infokey, value in dict_A.items():
... print key, \':\', value
...
blog : linuxzen.com
name : cold
1.7 字典键值互换
第一种,使用压缩器:
m = {\'a\': 1, \'b\': 2, \'c\': 3, \'d\': 4}
m.items()
[(\'a\', 1), (\'c\', 3), (\'b\', 2), (\'d\', 4)]
zip(m.values(), m.keys())
[(1, \'a\'), (3, \'c\'), (2, \'b\'), (4, \'d\')]
mi = dict(zip(m.values(), m.keys()))
mi
{1: \'a\', 2: \'b\', 3: \'c\', 4: \'d\'}
第二种,使用字典推导:
m = {\'a\': 1, \'b\': 2, \'c\': 3, \'d\': 4}
m
{\'d\': 4, \'a\': 1, \'b\': 2, \'c\': 3}
{v: k for k, v in m.items()}
{1: \'a\', 2: \'b\', 3: \'c\', 4: \'d\'}
二,使用dict(zip(key,value))
1。
传入映射对象做参数:dict(mapping,**kwargs)
1)传入的参数mapping是映射对象。是位置参数。
2)如果键有重名,后者的值将替代前者值。
例如:
k = [\'name\', \'age\', \'height\']
v = [\'齐德隆\', \'24\', \'187\']
worker=zip(k,v)
d1 = dict(worker)
print(d1)
{\'name\': \'齐德隆\', \'age\': \'24\', \'height\': \'187\'}
2。
传入可迭代的对象做参数:dict. (iterable,**kwargs)
1)参数 iterable 是可迭代的对象;是位置参数。
2)iterable的每个元素应是两个子元素的可迭代对象,如:[( a , 1 ) , ( b , 2 )]
3)每个元素中的第一个子元素将成为字典的键,第二个子元素成为值。
4)如果键有重名,后者的值将替代前者的值。
例如(PS:这例子是个什么鬼?):
worker=[(\'name\',\'齐德隆\'),(\'age\',24),(\'height\',187)]
d1=dict(worker)
print(d1)
{\'name\': \'齐德隆\', \'age\': 24, \'height\': 187}
Dictionary Methods
| METHODS | DESCRIPTION | 功能 |
|---|---|---|
| copy() | They copy() method returns a shallow copy of the dictionary. | 浅复制(指向同一内存地址) |
| clear() | The clear() method removes all items from the dictionary. | 清除字典所有内容 |
| pop() | Removes and returns an element from a dictionary having the given key. | 给定KEY删除元素并返回 |
| popitem() | Removes the arbitrary key-value pair from the dictionary and returns it as tuple. | 删除键值对并返回该元组 |
| get() | It is a conventional method to access a value for a key. | 按KEY查找VALUE |
| dictionary_name.values() | returns a list of all the values available in a given dictionary. | 返回字典内所有VALUE |
| str() | Produces a printable string representation of a dictionary. | 返回字符串形式的DICT(一个KEY-VALUE连一个那种) |
| update() | Adds dictionary dict2’s key-values pairs to dict | 更新键值对 |
| setdefault() | Set dict[key]=default if key is not already in dict | 与get()类似,但它新建不存在的键 |
| keys() | Returns list of dictionary dict’s keys | 列举所有KEY |
| items() | Returns a list of dict’s (key, value) tuple pairs | 列举所有KEY-VALUE,以元组形式 |
| has_key() | Returns true if key in dictionary dict, false otherwise | 检查DICT里是否有某KEY |
| fromkeys() | Create a new dictionary with keys from seq and values set to value. | 用seq作KEY,对应同一个value |
| type() | Returns the type of the passed variable. | 返回变量类型 |
| cmp() | Compares elements of both dict. | 对比两个字典 |