一、字典
1、创建字典
使用dict()
利用已有数据创建字典:
keys = ['a','b','c','d']
values = [1,2,3,4]
dic = dict(zip(keys,values))
print(dic)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
以给定内容为键,创建值为空的字典:
dic = dict.fromkeys(['a','b','c'])
print(dic)
{'a': None, 'b': None, 'c': None}
2、读取字典元素
使用字典对象的get方法获取指定键对应的值,并且可以在键不存在的时候返回指定值:
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print("a:" + str(dic['a']))
print("b:" + str(dic.get('b')))
print("e:" + str(dic.get('e')))
print("f:" + str(dic.get('f',6)))
print(dic)
dic['g'] = dic.get('g',[])
dic['g'].append(7)
print(dic)
区别:我们注意到运行dic.get('f',6)之后,并没有将{'f': 6}键值对存入dic字典中,与setdefault()方法略有不同,setdefault() 返回的键如果不在字典中,会添加键(更新字典),而 get() 不会添加键。
a:1
b:2
e:None
f:6
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'g': [7]}
使用字典对象的setdefault()
方法返回指定“键”对应的“值”,如果字典中不存在该“键”,就添加一 个新元素并设置该“键”对应的“值”:
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
dic.setdefault('e',5)
print(dic)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
使用字典对象的keys()方法可以返回字典的键列表:
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print("第一种方法:")
for key in dic: # 使用这个方式只能输出key
print(key+':'+str(dic[key]))
print("第二种方法:")
for key in dic.keys():
print(key+':'+str(dic[key]))
print(dic.keys())
第一种方法:
a:1
b:2
c:3
d:4
第二种方法:
a:1
b:2
c:3
d:4
dict_keys(['a', 'b', 'c', 'd'])
使用字典对象的values()方法可以返回字典的值列表:
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print("输出字典值:")
for value in dic.values():
print(value)
print(dic.values())
输出字典值:
1
2
3
4
dict_values([1, 2, 3, 4])
使用字典对象的items()方法可以返回字典的键、值对列表:
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print("输出字典键值对:")
for item in dic.items():
print(item)
print(dic.items())
输出字典键值对:
('a', 1)
('b', 2)
('c', 3)
('d', 4)
dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
3、添加字典元素
使用字典对象的update()方法将另一个字典的键、值对添加到当前字典对象:
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
dic.update({'abc':123})
print(dic)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'abc': 123}
4、删除字典元素
使用字典对象的popitem() 方法返回并删除字典中的最后一对键和值:
dic = {'url': 'www.neuedu.com', 'title': 'python web site', 'study': 'python'}
print(dic.popitem())
print(dic.popitem())
('study', 'python')
('title', 'python web site')
5、有序字典
Python内置字典是无序的,如果需要一个可以记住元素插入顺序的字典,可以使用
collections.OrderedDict:
import collections
x = dict() #无序字典
x['a'] = 3
x['b'] = 5
x['c'] = 1
print(x)
x = collections.OrderedDict()
x['a'] = 3
x['b'] = 5
x['c'] = 1
print(x)
{'a': 3, 'b': 5, 'c': 1}
OrderedDict([('a', 3), ('b', 5), ('c', 1)])
6、字典推导式
# 用字典推导式以字符串以及其索引位置建字典
strings = ['import','is','with','if','file','exception','impossible']
a = {val:num for num,val in enumerate(strings)}
print(a)
b = {strings[i]:len(strings[i])for i in range(len(strings))}
print(b)
c = {val:len(val) for val in strings}
print(c)
{'import': 0, 'is': 1, 'with': 2, 'if': 3, 'file': 4, 'exception': 5, 'impossible': 6}
{'import': 6, 'is': 2, 'with': 4, 'if': 2, 'file': 4, 'exception': 9, 'impossible': 10}
{'import': 6, 'is': 2, 'with': 4, 'if': 2, 'file': 4, 'exception': 9, 'impossible': 10}