Python字典
来源:互联网 发布:软件的硬件要求 编辑:程序博客网 时间:2024/06/05 16:27
创建字典:
phonebook={'Alice': '2341', 'Tome': '2302', 'Jack': '0921'}
空字典:
nonedict={}
dict函数:
>>> items = [('name', 'Gmby'), ('age', 42)]
>>> d = dict(items)
>>> d
{'age': 42, 'name': 'Gmby'}
>>> d['name']
'Gmby'
>>>
>>>
>>>
>>> d = dict (name='Tom', age = 33)
>>> d
{'age': 33, 'name': 'Tom'}
字典中键是唯一的,但是值可以有多个,就像存储个人信息时。例如:
people = {
'Alice': {
'phone' : '2354',
'addr' : 'cd'
}
'Tom': {
'phone': '0937',
'addr' : 'sdjfi'
}
}
字典方法:
clear()
x = {}
x.clear()
将所有相关字典都清空。
copy()
返回一个具有相同键值对的新字典,是浅复制。
deepcopy()是深复制
d = {}
c=d.copy()
dc = deepcopy(d)
fromkeys:使用给定的键建立新的字典,每个键默认对应的值为None。
>>> {}.fromkeys(['name', 'age'])
{'age': None, 'name': None}
>>>
>>> dict.fromkeys(['name', 'age'])
{'age': None, 'name': None}
>>> dict.fromkeys(['name', 'age'], '(unknown)')
{'age': '(unknown)', 'name': '(unknown)'}
>>>
get方法:
访问字典项的方法。若字典中不存在该项,不会出错,只是返回None。
items方法:
将字典中所有项以键值对的方式返回。
iteritems方法:
与items方法类似,但是它返回一个迭代器对象,而非键值对。
d = {}
it = d.iteritems()
pop方法:
d.pop('key')
返回给定键对应的值,然后将这个键值对从字典中删除。
popitem方法:
弹出字典中的随机项,与list.pop类似。
- Python 字典
- python 字典
- Python:字典
- Python 字典
- python字典
- Python 字典
- python 字典
- python 字典
- Python 字典
- Python字典
- python 字典
- python字典
- python 字典
- python 字典
- python--字典
- python 字典
- python字典
- Python---字典
- PAT 02-线性结构2 一元多项式的乘法与加法运算 (java)
- Bugly升级SDK适配Android N
- SSH Action使用ModelDriver实现最简单的增册改查
- 【POJ1177】【HDU1828】【codevs2149】矩形面积周长并
- spring_(1)学习
- Python字典
- 我的Android开发环境--Linux Mint
- Python 基础回顾(二)
- Hive 中数据库表的分区建议
- linux下使用c语言访问mySql数据库
- 文件系统显示用户名和路径
- 15. 3Sum M
- 九月英语总结
- 数据结构—概述