|
字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的。可哈希表示key必须是不可变类型,如:数字、字符串、元组。
字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
创建字典:
shop = {'iphone':2000,'book':'python'}
shop2 = dict((('iphone7s','new'),))
print(shop)
print(shop2)
输出:
{'iphone': 2000, 'book': 'python'}
{'iphone7s': 'new'}
对应操作:
1、增
shop = {}
shop['iphone7s'] = 'new'
shop['price'] = 8000
print(shop)
shop1 = shop.setdefault('price',9000)#键存在,不改动,返回字典中相应的键对应的值
print(shop1)
shop2 = shop.setdefault('buy','JD')#键不存在,在字典中中增加新的键值对,并返回相应的值
print(shop2)
print(shop)
输出:
{'iphone7s': 'new', 'price': 8000}
8000
JD
{'iphone7s': 'new', 'price': 8000, 'buy': 'JD'}
2、查
shop = {'iphone7s': 'new', 'price': 8000, 'buy': 'JD'}
print(shop.items())
print(shop.keys())
print(shop.values())
print(shop['buy'])
print(shop.get('buy',False))
print(shop.get('buys',False))
print('buy' in shop)
print(list(shop.values()))
输出:
dict_items([('iphone7s', 'new'), ('price', 8000), ('buy', 'JD')])
dict_keys(['iphone7s', 'price', 'buy'])
dict_values(['new', 8000, 'JD'])
JD
JD
False
True
['new', 8000, 'JD']
3、改
shop = {'iphone7s': 'new', 'price': 8000, 'buy': 'JD'}
shop['iphone7s'] = 'old'
shop1 = {'iphone5':'True','size':500}
shop.update(shop1)
print(shop)
输出:
{'iphone7s': 'old', 'price': 8000, 'buy': 'JD', 'iphone5': 'True', 'size': 500}
4、删
shop = {'iphone7s': 'old', 'price': 8000, 'buy': 'JD', 'iphone5': 'True', 'size': 500}
del shop['size']#删除字典中指定键值对
print(shop)
shop1 = shop.pop('iphone5')#删除字典中指定键值对,并返回该键值对的值
print(shop1)
print(shop)
shop2 = shop.popitem()#随机删除某组键值对,并以元组方式返回值
print(shop2)
print(shop)
shop.clear()# 清空字典
print(shop)
输出:
{'iphone7s': 'old', 'price': 8000, 'buy': 'JD', 'iphone5': 'True'}
True
{'iphone7s': 'old', 'price': 8000, 'buy': 'JD'}
('buy', 'JD')
{'iphone7s': 'old', 'price': 8000}
{}
5、内置方法
dict.fromkeys
dic6=dict.fromkeys(['host1','host2','host3'],'test')
print(dic6)
dic6['host2']='abc'
print(dic6)
dic6=dict.fromkeys(['host1','host2','host3'],['test1','tets2'])
print(dic6)
dic6['host2'][1]='test3'
print(dic6)
输出:
{'host1': 'test', 'host2': 'test', 'host3': 'test'}
{'host1': 'test', 'host2': 'abc', 'host3': 'test'}
{'host1': ['test1', 'tets2'], 'host2': ['test1', 'tets2'], 'host3': ['test1', 'tets2']}
{'host1': ['test1', 'test3'], 'host2': ['test1', 'test3'], 'host3': ['test1', 'test3']}
dic={5:'555',2:'666',4:'444'}
print(5 in dic)
print(sorted(dic.items()))
输出:
True
[(2, '666'), (4, '444'), (5, '555')]
dic5={'name': 'joker', 'age': 18}
for i in dic5:
print(i,dic5)
for i,v in dic5.items():
print(i,v)
for item in dic5.items():
print(item)
输出:
name joker
age 18
name joker
age 18
('name', 'joker')
('age', 18)
补充:字典与字符串相互转换:
字典转换为字符串
a = {'a' : 1, 'b' : 2, 'c' : 3}
b = str(a)
print(type(b))
<class 'str'>输出结果为:
---------------------------------------------------------------
字符串转换为字典
a = "{'a' : 1, 'b' : 2, 'c' : 3}"
b = eval(a)
print(type(b))
<class 'dict'>输出结果为: |
|