python---字典

python—字典
参考:https://www.cnblogs.com/stuqx/p/7291948.html

一、字典:
字典是无序的,它不能通过偏移来存取。只能通过键值来存取。
字典 = {‘key’:vlaue} key:类似我们现实的钥匙。而vlaue则是锁。一个钥匙开启一个锁。

二、特点:
内部没有顺序,通过键值来读取内容,可嵌套,方便我们组织多种数据结构,并且可以原地修改里面的内容。

属于可变类型。

组成字典的键值必须是不可变的数据类型,比如,数字,字符串,元组等,列表等可变对象不能作为键。

1、创建字典。{} , dict()
info = {‘name’:‘lilei’,‘age’:20}
info = dict(name=‘lilei’,age=20)

root@kali:~/python/laowangpy# python
Python 2.7.3 (default, Mar 14 2014, 11:57:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> info = {'a':1,'b':2}
>>> info
{'a': 1, 'b': 2}
>>> 
>>> info['a']#查找特定键值内容
1
>>> 
>>> binfo = {'a':[1,2,3,4],'b':[5,6,7,8]}#创建字典
>>> binfo
{'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8]}
>>> binfo['a']#查找特定键值
[1, 2, 3, 4]
>>> binfo['a'][2] = 12#变更键值的对应内容
>>> binfo
{'a': [1, 2, 12, 4], 'b': [5, 6, 7, 8]}
>>> 

>>> cinfo = {1:'22',2:'dd'}#使用数字,新建字典
>>> cinfo
{1: '22', 2: 'dd'}
>>> dinfo = {'22':'2222','aa':'333'}#使用字符串,新建字典
>>> dinfo
{'aa': '333', '22': '2222'}
>>> einfo = {(1,2,3,4):'ss',('b','d'):'555'}#使用元组,新建字典
>>> einfo
{(1, 2, 3, 4): 'ss', ('b', 'd'): '555'}
>>> 
>>> 
>>> finfo = {[1,2,3,4]:'rrr'}#使用列表,新建字典
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> 
>>> ginfo = {(1,'a':'23')}
  File "<stdin>", line 1
    ginfo = {(1,'a':'23')}
                   ^
SyntaxError: invalid syntax
>>> ginfo = {(1,'a'):'23'}
>>> ginfo
{(1, 'a'): '23'}
>>> hinfo = {(1,'a',[1,2,3]):'23'}#使用存在列表的元组,新建字典。谨记元组中元素必须是不可变类型。
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> 
>>> xinfo = {(1,"2",[2,3]):'a'}#包含list()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> xinfo = {(1,"2"):'a'}
>>> xinfo
{(1, '2'): 'a'}

创建字典 {},dict()

>>> 
>>> info = {'name':'lilei','age':20}
>>> info
{'age': 20, 'name': 'lilei'}
>>> binfo = dict(name='lilei',age=20)
>>> binfo
{'age': 20, 'name': 'lilei'}
>>> 
>>> 

2、添加内容 a[‘xx’] = ‘xx’
比如 info[‘phone’] = ‘iphone5’

>>> 
>>> info['phone'] = 'iphone5s'#在字典中增加键与值信息
>>> info
{'phone': 'iphone5s', 'age': 20, 'name': 'lilei'}
>>> info['phone'] = 'htc'#把value值变更成其他值。谨记在字典中存在的值赋值就变更,不存在的值赋值时就是增加
>>> info
{'phone': 'htc', 'age': 20, 'name': 'lilei'}
>>> 
>>> 

3、修改内容 a[‘xx’] = ‘xx’
info[‘phone’] = ‘htc’
update 参数是一个字典的类型,也会覆盖相同键的值
info.update({‘city’:‘beijing’,‘phone’:‘nokia’})
htc变成了nokia了

>>> binfo
{'age': 20, 'name': 'lilei'}
>>> binfo.update({'city':'beijing','phone':'nokia'})
>>> binfo
{'city': 'beijing', 'age': 20, 'name': 'lilei', 'phone': 'nokia'}
>>> binfo.update({'city':'beijing','phone':'sangxing'})
>>> binfo
{'city': 'beijing', 'name': 'lilei', 'phone': 'sangxing', 'age': 20}

4、删除 del、clear、pop
del info[‘phone’] 删除某个元素
info.clear()删除字典的全部元素
info.pop(‘name’) 传入键名,pop出键名对应的值,并且把这个键名与对应值从字典中删除。列表Pop()是索引的下标,字典pop()是键名。

>>> 
>>> ainfo = {'age':22,'name':'lilei'}
>>> ainfo
{'age': 22, 'name': 'lilei'}
>>> del ainfo['name']#删除某个元素
>>> ainfo
{'age': 22}
>>> 
>>> del ainfo#删除整个字典
>>> ainfo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ainfo' is not defined
>>>

>>> 
>>> a = {'name':'lilei','age':22}
>>> a
{'age': 22, 'name': 'lilei'}
>>> a.clear()#把整个字典中所有元素清空
>>> a
{}
>>> 

>>> 
>>> binfo = []
>>> binfo
[]
>>> binfo.append('ww')
>>> binfo.append('22')
>>> binfo
['ww', '22']
>>> binfo.pop('22')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>> binfo.pop(22)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range
>>> binfo.pop(0)#列表Pop()是索引的下标,字典pop()是键名
'ww'
>>> binfo
['22']
>>> 

>>> 
>>> a = [1,2,3,4]
>>> a
[1, 2, 3, 4]
>>> a.pop(0)
1
>>> a
[2, 3, 4]
>>> a.pop(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range
>>> b = {'22':'aa','33':'bb'}
>>> b
{'33': 'bb', '22': 'aa'}
>>> b.pop('55')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: '55'
>>> b.pop('66':'rr')
  File "<stdin>", line 1
    b.pop('66':'rr')
              ^
SyntaxError: invalid syntax
>>> b
{'33': 'bb', '22': 'aa'}
>>> b.pop('66','rr')
'rr'
>>> b
{'33': 'bb', '22': 'aa'}
>>> 

5、in 和has_key() 成员关系操作(只查询键名是否在字典中)
比如:
1 phone in info
2 info.has_key(‘phone’)
6 keys():返回的是列表,里面包含了字典的所有键
values():返回的是列表,里面包含了字典的所有值

>>> 
>>> a = {'name':'lilei','phone':'nokia'}
>>> a
{'phone': 'nokia', 'name': 'lilei'}
>>> 'name' in a
True
>>> 'lilei' in a
False
>>> 'xxx' in a
False
>>> a.has_key('name')
True
>>> a.has_key('nokia')
False
>>> a.has_key('lilei')
False
>>> a.has_key('xx')
False
>>> 

>>> 
>>> ainfo = {"name":'liming','age':22}
>>> ainfo
{'age': 22, 'name': 'liming'}
>>> ainfo.keys()
['age', 'name']
>>> ainfo.values()
[22, 'liming']
>>> 
>>> ainfo.items()#生成元组
[('age', 22), ('name', 'liming')]
>>> 

7、get方法
info.get(‘name’)
info.get(‘age2’,‘22’)

>>> ainfo
{'age': 22, 'name': 'liming'}
>>> ainfo.get('22')
>>> ainfo
{'age': 22, 'name': 'liming'}
>>> ainfo.get('dd')
>>> ainfo
{'age': 22, 'name': 'liming'}
>>> b = ainfo.get('33')
>>> b
>>> type(b)
<type 'NoneType'>
>>> 
>>> ainfo.get('22','abc')
'abc'
>>> 

http://blog.csdn.net/moodytong/article/details/7647684
Python学习之字典详解

在元组和列表中,都是通过编号进行元素的访问,但有的时候我们按名字进行数据甚至数据结构的访问,在c++中有map的概念,也就是映射,在python中也提供了内置的映射类型–字典。映射其实就是一组key和value以及之间的映射函数,其特点是:key的唯一性、key与value的一对多的映射。
1.字典的创建
字典的基本形态dic={key1:value1, key2:value2…}
创建方式1:直接型。
dict1={}
dict2={‘name’:‘earth’,‘port’:‘80’}
创建方式2:使用工厂方法dict,通过其他映射(例如字典)或者(键,值)这样的序列对建立
items=[(‘name’,‘earth’),(‘port’,‘80’)]
dict2=dict(items)
dict1=dict(([‘name’,‘earth’],[‘port’,‘80’]))
创建方式3:使用内建方法fromkeys()创建’默认‘字典,字典中元素具有相同的value(如果没有给出,默认为none)
dict1={}.fromkeys((‘x’,‘y’),-1)
#dict={‘x’:-1,‘y’:-1}
dict2={}.fromkeys((‘x’,‘y’))
#dict2={‘x’:None, ‘y’:None}
2.访问字典中的值
最常用和基本的莫过于利用key访问value了
a.通过key访问value之get方法
dict1.get(‘name’)#也可以直接是dictionary[‘key1’],但是当key1不存在其中时,会报错;此时用get则返回None
b.随机访问其中键值对
字典中是无序的,利用popitem方法是随机弹出一个键值对
c.返回字典所有值的列表
方法values
3.访问字典中的key
a.检查是否含有key1
dictionary.has_key(key1)
key1 in dictionarty
key1 not dictionary
b.返回字典中键的列表
dictionary.keys()
4.访问键值对
a.遍历方式
for r in dicitonary #r是dictionary中的键值对
b.修改(更新)或添加
dictionary[key1]=value1
5.删除
a.按key删除
del dictionary[key1]
b.删除并返回
dictionary.pop(key1)
c.删除所有项
dictionary.clear()
del dictionary
6.排序
sorted(dic.iteritems(), key=lambda d:d[1], reverse=False)
说明:对字典dic中的元素按照d1进行升序排序,通过设置reverse的True或False可以进行逆序,并返回排序后的字典(该排序后的字典由元组组成,其形式为[(key1,value1),(key2,value2),…],且原字典保持不变)
7.其他
len(dictionary) #返回字典项个数
dictionary.item()
dictionary.iteritems()

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

徐为波

看着给就好了,学习写作有点累!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值