python学习笔记字典
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习笔记字典相关的知识,希望对你有一定的参考价值。
字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的。可哈希表示key必须是不可变类型,如:数字、字符串、元组。
字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。
创建字典:
= {::} shop2 = ((())) () (shop2)
输出:
{‘iphone‘: 2000, ‘book‘: ‘python‘}
{‘iphone7s‘: ‘new‘}
对应操作:
1、增
= {} [] = [] = () shop1 = .setdefault()(shop1) shop2 = .setdefault()(shop2) ()
输出:
{‘iphone7s‘: ‘new‘, ‘price‘: 8000}
8000
JD
{‘iphone7s‘: ‘new‘, ‘price‘: 8000, ‘buy‘: ‘JD‘}
2、查
= {: : : } (.items()) (.keys()) (.values()) ([]) (.get()) (.get()) () ((.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、改
= {: : : } [] = shop1 = {::} .update(shop1) ()
输出:
{‘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
=.fromkeys([]) () []=() =.fromkeys([][]) () [][]=()
输出:
{‘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‘]}
={:::} () ((.items()))
输出:
True
[(2, ‘666‘), (4, ‘444‘), (5, ‘555‘)]
={: : } i : (i[i]) iv .items(): (iv) item .items(): (item)
输出:
name joker
age 18
name joker
age 18
(‘name‘, ‘joker‘)
(‘age‘, 18)
本文出自 “on_the_road” 博客,请务必保留此出处http://cqtesting.blog.51cto.com/8685091/1958821
以上是关于python学习笔记字典的主要内容,如果未能解决你的问题,请参考以下文章