Python——字典建立操作

主要内容来源:http://www.jb51.net/article/47990.htm

一、字典的建立:

>>> dict={'Alice':123,'Cecil':456}
>>> dict
{'Alice': 123, 'Cecil': 456}

  注意:键必须是独一无二的,值不必

二、访问字典的值  

>>> dict['Alice']
123
字典中不存在此键的情况,将报错
>>> dict['mlice'] Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> dict['mlice'] KeyError: 'mlice'

三、修改字典

1 >>> dict['Age'] = 8; # update existing entry
2 >>> dict['School'] = "DPS School"; #Add new entry
1 >>> dict
2 {'Age': 8, 'Name': 'Zara', 'Class': 'First'}

四、删除字典

1)删除相应的条目

1 >>> dict
2 {'Age': 8, 'Name': 'Zara', 'Class': 'First'}
3 >>> del dict['Name']
4 >>> dict
5 {'Age': 8, 'Class': 'First'}

2)清空所有的条目

1 >>> dict.clear()
2 >>> dict
3 {}

3)删除字典

>>> del dic
>>> dic

Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    dic
NameError: name 'dic' is not defined

 五、字典的键的属性

1)字典的键仅允许出现一次,如果出现两次,后面的键对应的值会将前面的键的值覆盖 

>>> dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
>>> dict['Name']
'Manni'
>>> dict
{'Age': 7, 'Name': 'Manni'}

2)键的值是不可变的,所以可以使用数字、字符串、元组,不可以用列表

1 >>> dict = {['Name']: 'Zara', 'Age': 7};
2 
3 Traceback (most recent call last):
4   File "<pyshell#6>", line 1, in <module>
5     dict = {['Name']: 'Zara', 'Age': 7};
6 TypeError: unhashable type: 'list'

六、字典内置函数、方法

1)内置的函数

len(dict) #计算字典圆度的个数,即字典的键的个数

str(dict)#将返回字典的字符型表示

type(variable)#返回输入变量的类型

1 >>> dic
2 {'Alice': 123, 'Cecil': 456}
3 >>> type(dic)
4 <type 'dict'>

2)方法

dict.fromkeys()#创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值

http://www.runoob.com/python/att-dictionary-fromkeys.html

1 >>> dic.fromkeys([1,2,3],[4,5,6])
2 {1: [4, 5, 6], 2: [4, 5, 6], 3: [4, 5, 6]}

dict.get(key,default=None)

>>> dic
{'Alice': 123, 'Cecil': 456}
>>> dic.get('Alice')
123
>>> dic.get('Alic')
>>> dic.get('Alic','no')
'no'

dict.setdefault(key,default=None)和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default

1 >>> dic
2 {'Alice': 123, 'Cecil': 456}
3 >>> dic.setdefault('zhang')
4 >>> dic
5 {'zhang': None, 'Alice': 123, 'Cecil': 456}
6 >>> dic.setdefault('zhang',1)
7 >>> dic
8 {'zhang': None, 'Alice': 123, 'Cecil': 456}

dict.has_key(key)

1 >>> dic.has_key('Alice')
2 True

dict.items()以列表的形式返回可便利的(键、值)元组数组;dict.keys()返回字典所有的键;dict.values()返回字典所有的值

1 >>> dic.items()
2 [('Alice', 123), ('Cecil', 456)]
3 >>> dic.keys()
4 ['Alice', 'Cecil']
>>> dic.values()
[123, 456]

dic1.update(dic2) 把字典dic2的键/值对更新到dict1里

1 >>> dic
2 {'Alice': 123, 'Cecil': 456}
3 >>> dic1={}
4 >>> dic1.update(dic)
5 >>> dic1
6 {'Alice': 123, 'Cecil': 456}

    

原文地址:https://www.cnblogs.com/liuting1990/p/6511238.html