ljzsdut
GitHubToggle Dark/Light/Auto modeToggle Dark/Light/Auto modeToggle Dark/Light/Auto modeBack to homepage

09 字典

	字典在其他编程语言中又称之为关联数组或散列表。字典是一种映射(mapping)类型(将键映射到值)。字典是Python核心对象集合中的唯一的一种映射,也具有可变性——可以就地改变,并可以随需求增大或减小。和列表一样,字典存储的是对象引用(不是拷贝)。

​ 字典定义使用表达式符号:花括号{},通过键(而不是索引/偏移)实现元素存取、修改,无序集合,可变类型的容器,长度可变支持异构和嵌套。

新版本中,字典是有序的,顺序为插入key/value的顺序。

定义

1、使用{}定义字典。格式:{key1:value1,key2:value2…}

2、dict()构造函数

>>> a = {'one': 1, 'two': 2, 'three': 3}
>>> b = dict(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})
>>> a == b == c == d == e
True

zip的用法:

zip(seq1 [, seq2 [...]]) 返回元组列表python3返回zip对象), [(seq1[0], seq2[0] ...), (...)]
>>> zip('xyz','123')
[('x', '1'), ('y', '2'), ('z', '3')]
>>> zip('xyz',[12,23,34])
[('x', 12), ('y', 23), ('z', 34)]
>>> zip('xyz',[12,23,34],['aa','bb','cc'])
[('x', 12, 'aa'), ('y', 23, 'bb'), ('z', 34, 'cc')]

操作与方法

>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> list(d)  #key的列表
['one', 'two', 'three', 'four']
>>> len(d)
4


#获取key
>>> d.get("one")   
1
>>> d.get("five",5)  #如果key不存在,则返回默认值。缺少默认值为None。永不抛异常。
5
>>> d.get("five")

>>> d["two"]
2
>>> d["five"]  #如果key不存在,则抛出异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'five'

 
#增改
>>> d['four']='四'
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': '四'}

# 删
>>> del d["four"]
>>> d
{'one': 1, 'two': 2, 'three': 3}

>>> d.pop("one")
1
>>> d
{'two': 2, 'three': 3}

>>> d.popitem()  #LIFO,先进后出
('three', 3)


# 判断key存在性
>>> 'one' in d
False
>>> 'one' not in d
True

#浅拷贝;如果要深拷贝,使用copy.deepcopy()
>>> d1=d.copy()  
>>> d1
{'two': 2}

#清空字典
>>> d1.clear()  
>>> d1
{}

#添加item,并设置默认值(如果key已经存在,则忽略;如果不存在,则添加)
>>> d
{'two': 2}
>>> d.setdefault("two",22)
2
>>> d.setdefault("five")
>>> d.setdefault("six",6)
6
>>> d
{'two': 2, 'five': None, 'six': 6}

# 构造value一致的dict
>>> d1=dict.fromkeys(["one","two","three"])
>>> d1
{'one': None, 'two': None, 'three': None}
>>> d1=dict.fromkeys(["one","two","three"],11)
>>> d1
{'one': 11, 'two': 11, 'three': 11}

# 更新或添加item
>>> d
{'two': 2, 'five': None, 'six': 6}
>>> d.update(d1)
>>> d
{'two': 11, 'five': None, 'six': 6, 'one': 11, 'three': 11}


# 迭代器
>>> iter(d)
<dict_keyiterator object at 0x106c56fb0>
>>> iter(d.keys())
<dict_keyiterator object at 0x106c7a0b0>


# 视图
>>> d.keys()
dict_keys(['two', 'five', 'six', 'one', 'three'])
>>> d.values()
dict_values([11, None, 6, 11, 11])
>>> d.items()
dict_items([('two', 11), ('five', None), ('six', 6), ('one', 11), ('three', 11)])
>>>
>>> for i in d.values():
...   print(i)
...
11
None
6
11
11

字典的遍历

遍历key值

>>> a
{'a': '1', 'b': '2', 'c': '3'}
>>> for key in a:
       print(key+':'+a[key])
 
a:1
b:2
c:3
>>> for key in a.keys():
       print(key+':'+a[key])
 
a:1
b:2
c:3

在使用上,for key in afor key in a.keys():完全等价。

遍历value值

>>> for value in a.values():
       print(value)
 
1
2
3

遍历字典项item

>>> for kv in a.items():
       print(kv)
 
('a', '1')
('b', '2')
('c', '3')

遍历字典key-value

>>> for key,value in a.items():
       print(key+':'+value)
 
a:1
b:2
c:3
>>> for (key,value) in a.items():
       print(key+':'+value)
 
a:1
b:2
c:3

在使用上for key,value in a.items()for (key,value) in a.items()完全等价

变量解包

变量解包:将集体对象中的多个值同时赋值给多个变量,需要注意左右两边元素数量必须相等

>>> t1,t2=[1,2]
>>> print t1
1
>>> print t2
2


>>> dict1
{'a': 1, 'c': 3, 'b': 11, 'd': 4}
>>> for k,v in dict1.items():
...   print(k,v)
...
a 1
c 3
b 11
d 4

字典解析/推导

>>> D = {x:x*2 for x in range(10)}
>>> D
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}

使用细节

在最近版本的Python中,通过使用最新的sorted内置函数可以一步完成。sorted调用返回结果并对各种对象类型进行排序,对于字典而言,会自动对字典的键排序:

>>> dict1={'a': 1, 'c': 3, 'b': 11, 'd': 4}
>>> for i in sorted(dict1):
...     print i,"==>",dict1[i]
...
a ==> 1
b ==> 11
c ==> 3
d ==> 4