一、Dictionary简介
Dictionary是Python中的一种数据结构,能够映射key和value。
例:
key value
1------>2
2------>3
4------>3
-Dictionary中的value可以是任何数据结构,可以是数值,string,list等。
-但Diction中的key必须是immutable的,所以key的数据类型不可以是list,但可以是tuple
-每个key只能映射到一个value,但同一个value可以被很多key映射到。
二、创建一个Dictionary
1.直接创建,语法如下:
empty = {}
simple = {1: 2}
squares = {1: 1, 2: 4, 3: 9, 4: 16}
cipher = {'p': 'o', 'y': 'h', 't': 'n',
'h': 't', 'o': 'y', 'n': 'p'}
goodinstructors = {'Rixner': True, 'Warren': False}
cities = {'China': ['Shanghai', 'Beijing'],
'USA': ['New York', 'Los Angeles'],
'Spain': ['Madrid', 'Barcelona'],
'Australia': ['Sydney', 'Melbourne'],
'Texas': ['Houston', 'San Antonio']}
2.使用dict()函数创建:
empty2 = dict()
print(empty2)
data = [(1, 'one'), (2, 'two'), (3, 'three')]
names = dict(data)
print(names)
cipher2 = dict(cipher)
print(cipher2)
-直接dict()函数不带参数会创建一个空的dictionary
-可以传入一个元素由配对的元祖组成的list,自动生成对应的dictionary。每一个tuple会被识别为一个键值对(key-value pair)
-dict()可以传入 一个dictionary,复制出一个相同的dictionary
输出结果为:
三、查找和更新Dictionary
1.在一个dictionary中查找key对应的value
cipher = {'p': 'o', 'y': 'h', 't': 'n',
'h': 't', 'o': 'y', 'n': 'p'}
print(cipher)
# Use indexing with keys to access values
print(cipher['t'])
print(cipher['n'])
输出结果为:
P.S.当你试图找一个不存在的key对应的value时,程序会报错
cipher = {'p': 'o', 'y': 'h', 't': 'n',
'h': 't', 'o': 'y', 'n': 'p'}
#这句会报错
print(cipher[1])
2.Dictionary中的get()方法
Get()方法适用于当你想找一个key对应的value,且你并不确定这个key是否存在于dictionary中时。
cipher = {'p': 'o', 'y': 'h', 't': 'n',
'h': 't', 'o': 'y', 'n': 'p'}
print(cipher.get('t')) #输出结果为n
print(cipher.get(1)) #输出结果为None
print(cipher.get(1, 'z')) #输出结果为z
-当get中的key确实存在于dictionary中时,返回对应的value
-当get中传入的key不存在于dictionary中时,返回None
-当get中传入两个参数时,表示当key不存在于dictionary中时,返回第二个参数。例cipher.get(1,'z'),cipher中不存在1这个key,因此返回值为z
3.更新dictionary中的key->value map
cipher = {'p': 'o', 'y': 'h', 't': 'n',
'h': 't', 'o': 'y', 'n': 'p'}
print(cipher)
# Modify an existing key->value mapping
cipher['p'] = 'q'
print(cipher)
# Create a new key->value mapping
cipher['r'] = 'z'
print(cipher)
更改和添加键值对的语法很相似,当传入的key已经存在于dictionary中时表现为修改这个key对应的value,如果传入的key不存在于dictionary中,则表现为为这个dictionary添加一个新的键值对。
输出结果为:
4.用in操作符判断一个key是否存在在dictionary中
mapping = {1: 5, 8: -3, 7: 22, 4: 13, 22: 17}
# Keys
print(1 in mapping) #输出结果为True
print(8 in mapping) #输出结果为True
# Values
print(5 in mapping) #输出结果为False
print(-3 in mapping) #输出结果为False
# Both
print(22 in mapping) #输出结果为True
# Neither
print(82 in mapping) #输出结果为False
四、Dictionary的一些其他操作
1.遍历一个dictionary
-只需要key的情况,直接遍历dictionary即可
def print_contacts(contacts):
"""
Print the names of the contacts in our contacts list.
"""
for name in contacts:
print(name)
-需要key,value的情况,需要用items()函数遍历:
def print_contact_list(contacts):
"""
Print the names and phone numbers of the contacts in
our contacts list.
"""
for name, number in contacts.items():
print(name, ":", number)
2.对一个dictionary进行排序
def print_ordered(contacts):
"""
Print the names and phone numbers of the contacts
in our contacts list in alphabetical order.
"""
keys = contacts.keys()
names = sorted(keys)
for name in names:
print(name, ":", contacts[name])
-keys()函数可以得到一个dictionary中所有key的list
-sorted()函数可以按照字母顺序将key排序