1.字典定义:
字典和列表类似 只是字典标示符用的是字符而列表用的是0开始的数字,字典中每个元素对应一个值 这个元素叫做键(key)键值不能重复 value(值)可以重复
2.字典格式:
格式一:
[Name]={‘key1’:’value1’,’key2’:’value2’,………}
例:
>>>dictionary={'key1':'value1','key2':'value2','key3':'value3'} >>>print (dictionary) {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
格式二:
[Name]={}
Name[‘key1’]=’value1’
Name[‘key2’]=’value2’
………
例:
>>> dictionary={} >>> dictionary['key1']='value1' >>> dictionary['key2']='value2' >>> dictionary['key3']='value3' >>> print (dictionary) {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
三、字典的方法
dict.keys() //查看字典中的键
>>> dictionary.keys() ['key3', 'key2', 'key1']
dict.get() //获取字典中指定键的值
>>> dictionary={'key1':'value1','key2':'value2','key3':'value3'} >>> dictionary.get("key1") value1
dict.values() //查看字典中所有的值
>>> dictionary.values() ['value3', 'value2', 'value1']
dict.items() //获取字典中所有键、值 以列表的方式输出 其中对应的键、值通过元组进行组合
#-*- coding:utf-8 -*- #/usr/bin/env python >>> dictionary={'key1':'value1','key2':'value2','key3':'value3'} >>> dictionary.items() [('key3', 'value3'), ('key2', 'value2'), ('key1', 'value1')]
dict.has_key //判断key是否存在如果存在则返回True 否则则返回False
>>> dictionary={'key1':'value1','key2':'value2','key3':'value3'} >>> dictionary.has_key('key1') True >>> dictionary.has_key('alan') False
dict.pop('key') //删除并返回key对应的值
>>> dictionary={'key1':'value1','key2':'value2','key3':'value3','key4':'value4'} >>> dictionary.pop('key1') 'value1' >>> dictionary {'key3': 'value3', 'key2': 'value2', 'key4': 'value4'}
dict.popitem() //随机删除并以元组的方式返回字典中的任意一个键值对
>>> dictionary={'key1':'value1','key2':'value2','key3':'value3','key4':'value5'} >>> dictionary.popitem() ('key3', 'value3') >>> dictionary {'key2': 'value2', 'key1': 'value1', 'key4': 'value5'}
dict['key'] = value //如果不存在键值则创建 如果存在则覆盖
>>> dictionary={'key1':'value1','key2':'value2','key3':'value3','key4':'value4'} >>> dictionary['key1']='alan' >>> dictionary {'key3': 'value3', 'key2': 'value2', 'key1': 'alan', 'key4': 'value4'}
dict.copy() //复制字典 在内存中重新开辟一块空间
>>> dictionary={'key2': 'value2', 'key4': 'value4'} >>> test = dictionary.copy() >>> test {'key2': 'value2', 'key4': 'value4'} #查看test对应的内存地址 >>> id(test) 45940000 #查看dictionary对应的内存地址 >>> id(dictionary) 45859440
注:
如果直接赋值 test = dictionary 那么他们将共享同一份内存数据
>>> test = dictionary >>> id(test) 45859440 >>> id(dictionary) 45859440