1.字典的"键"唯一不可修改(与字符串一样),"值"可变:
>>> d={[1,2]:3}
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
d={[1,2]:3}
TypeError: unhashable type: 'list'
- 字典是可变的,可以原地修改,而字符串和元组不行:
>>> ad={}
>>> id(ad)
50949832
>>> ad['name']='Jim Green'
>>> ad
{'name': 'Jim Green'}
>>> id(ad)
50949832
2.使用dict()转化为字典(传入的值必须符合'键-值'这样的内容):
- 利用元组构建字典
# 如果单个列表有3个元素,也是会报错
>>> name=(['first','sina'],['second','51cto'])
>>> website=dict(name)
>>> website
{'second': '51cto', 'first': 'sina'}
>>> name=('sina.com','qq.com')
>>> website=dict(name)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
website=dict(name)
ValueError: dictionary update sequence element #0 has length 8; 2 is required
>>> tuple3=(('name',20),)
>>> dict3=dict(tuple3)
>>> dict3
{'name': 20}
- 或者dict()传入键-值:
>>> message=dict(name='Jim Green',age=20)
>>> message
{'name': 'Jim Green', 'age': 20}
- 字典方法:dict.fromkeys()---传入可迭代对象和值,作出"多个键映射相同值的效果"
>>> help(dict.fromkeys)
Help on built-in function fromkeys:
fromkeys(iterable, value=None, /) method of builtins.type instance
Returns a new dict with keys from iterable and values equal to value.
>>> iterable1="string"
>>> value1=dict.fromkeys(iterable1,'对应字符串')
>>> value1
{'n': '对应字符串', 'g': '对应字符串', 't': '对应字符串', 's': '对应字符串', 'r': '对应字符串', 'i': '对应字符串'}
>>> iterable2=[1,2,3,4]
>>> value2=dict.fromkeys(iterable2,'对应数字')
>>> value2
{1: '对应数字', 2: '对应数字', 3: '对应数字', 4: '对应数字'}
# fromkeys()的值只有一个,无法对应
>>> value2=dict.fromkeys(iterable2,('1','2','3','4'))
>>> value2
{1: ('1', '2', '3', '4'), 2: ('1', '2', '3', '4'), 3: ('1', '2', '3', '4'), 4: ('1', '2', '3', '4')}
3.字典不关心顺序,所以也就没有索引和切片这种东东,记住啦~~~
- len(d),返回字典(d)中的键值对的数量:
>>> city_code={'suzhou': '0512', 'beijing': '011', 'shanghai': '012', 'tangshan': '0315'}
>>> len(city_code)
4
del d[key],删除字典(d)的键(key)项(将该键值对删除):
>>> del city_code['beijing']
>>> city_code
{'shanghai': '012', 'suzhou': '0512', 'tangshan': '0315'}
key in d,检查字典(d)中是否含有键为key的项:
>>> city_code
{'shanghai': '012', 'suzhou': '0512', 'tangshan': '0315'}
>>> 'shanghai' in city_code
True
>>> 'xiamen' in city_code
False
4.很"酷"的字典实现"格式化"功能:
>>> city_code={'hangzhou':"0521",'suzhou':"0639",'beijing':'010'}
# 键名添加到%s之间
>>> message='hangzhou is a beautiful city and its city code is %(hangzhou)s' % city_code
>>> message
'hangzhou is a beautiful city and its city code is 0521'
# 分别使用format和"%"
>>> dict1={'name':'Jim Green','age':20}
>>> "{name}'s age is {age}".format(**dict1)
"Jim Green's age is 20"
>>> "%(name)s's age is %(age)s" % dict1
"Jim Green's age is 20"
>>>
- 延伸到网页模板:
>>> temp="<html><head><title>%(lang)s</title><body><p>my name is %(name)s.</p></body></head></html>"
>>> message={'name':'Jim Green','lang':'python'}
>>> temp % message
'<html><head><title>python</title><body><p>my name is Jim Green.</p></body></head></html>'
5.python中,一个对象有两个标签(或者说两个变量)是很常见的:
>>> a=5
>>> b=a
>>> b
5
>>> id(a)
1774514096
>>> id(b)
1774514096
- 假装拷贝和字典的copy()方法:
# 假装拷贝
>>> dict1={'name':'Jim Green','age':20}
>>> dict2=dict1
>>> dict2
{'age': 20, 'name': 'Jim Green'}
>>> id(dict1)
51571400
>>> id(dict2)
51571400
# 使用copy,结果发现内存地址不一样了
>>> dict3=dict1.copy()
>>> dict3
{'age': 20, 'name': 'Jim Green'}
>>> id(dict3)
50953672
- python的"深拷贝"和'浅拷贝',看到再谷歌一下...
补充:
Help on class dict in module builtins:
class dict(object)
| dict() -> new empty dictionary
# dict1=dict()
# dict1={}
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
>>> list1=[('name','Jim Green'),('age',20)]
>>> dict1=dict(list1)
>>> dict1
{'age': 20, 'name': 'Jim Green'}
# 只要满足映射的关系即可
>>> tuple1=(['name','Jim Green'],['age',20],('breast',60))
>>> dict2=dict(tuple1)
>>> dict2
{'breast': 60, 'age': 20, 'name': 'Jim Green'}
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
# 见到这种处理方法,不要惊奇
>>> tuple1=(['name','Jim Green'],('age',20))
>>> d=dict()
>>> for k,v in tuple1:
d[k]=v
>>> d
{'name': 'Jim Green', 'age': 20}
>>> tuple1=(['name','Jim Green'],('age',20))
# 平常是这么处理
>>> d=dict(tuple1)
>>> d
{'name': 'Jim Green', 'age': 20}
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
- 浅拷贝和深拷贝
>>> x=dict(name='qiwsir',lang=['python','java','c'])
>>> y=x.copy()
>>> y
{'name': 'qiwsir', 'lang': ['python', 'java', 'c']}
# 地址不同,是两个对象
>>> id(x)
54001352
>>> id(y)
51343944
# y删除值为list元素,影响x
>>> y['lang'].remove('c')
>>> y
{'name': 'qiwsir', 'lang': ['python', 'java']}
>>> x
{'name': 'qiwsir', 'lang': ['python', 'java']}
# y重新赋值str元素,不影响x
>>> y['name']='laoqi'
>>> y
{'name': 'laoqi', 'lang': ['python', 'java']}
>>> x
{'name': 'qiwsir', 'lang': ['python', 'java']}
# x,y的lang键值为List类型,地址相同,指向同一个对象,一个变,另一个当然也变
>>> id(x['lang'])
53999112
>>> id(y['lang'])
53999112
# x,y的name键值为str类型,地址不同,是不同对象,互相独立
>>> id(x['name'])
53995032
>>> id(y['name'])
53995088
-----以上,就是所谓的"浅拷贝"------------
结论就是,拷贝完后,若值为"可变的",该值若更改,另一个对象该值也会跟着变
若值为不可变,则独立,不互相影响
Python在所执行的复制动作中,如果是基本类型的对象(专指数字和字符串),
就在内存中重新建个窝;如果不是基本类型的,就不新建窝了,而是用标签引用原来的窝。
# 使用copy库,实现深度拷贝,互相独立
>>> x
{'name': 'qiwsir', 'lang': ['python', 'java']}
# 深拷贝
>>> import copy
>>> z=copy.deepcopy(x)
>>> z
{'name': 'qiwsir', 'lang': ['python', 'java']}
# 果然,地址不一样了
>>> id(x['lang'])
53999112
>>> id(z['lang'])
51361992
# 删除可变键值试试,结果果然是独立的
>>> x['lang'].remove('java')
>>> x
{'name': 'qiwsir', 'lang': ['python']}
>>> z
{'name': 'qiwsir', 'lang': ['python', 'java']}
# 添加可变键值,结果也没有意外
>>> x['lang'].append('C++')
>>> x
{'name': 'qiwsir', 'lang': ['python', 'C++']}
>>> z
{'name': 'qiwsir', 'lang': ['python', 'java']}