您的位置:首页 > 编程语言 > Python开发

python基础学习之字典

2017-04-26 12:11 330 查看
字典特性:

1.是用大括号括起来的

2.不是序列类型,是映射

 

>>> brand = ['1','2','3','4','5']

>>> slogan=['aaa','bbb','ccc','ddd','eee']

>>> print('3 is for '+slogan[brand.index('3')])

3 is for ccc

很不方便。

1.字典由键和值组成,冒号前是键,冒号后是其值,访问的时候可以使用键来访问其值。

>>> isfor ={'1':'aaa','2':'bbb','3':'ccc','4':'ddd','5':'eee'}

>>> print('3 is for'+isfor['3'])

3 is forccc

 

>>> isfor

{'1': 'aaa', '2': 'bbb', '3': 'ccc', '4': 'ddd', '5': 'eee'}

>>> isfor['2']

'bbb'

 

2.可以给键赋值,如果此键不存在则会为其创建键与值。

 

3. class dict(object)

dict()-> new empty dictionary

dict(mapping)-> new dictionary initialized from a mapping object's  (key, value) pairs

dict(iterable)-> new dictionary initialized as if via:

       d = {}

      for k, v in iterable:

          d[k] = v

dict(**kwargs)-> new dictionary initialized with the name=value pairs  in the keyword argument list.  For example: dict(one=1, two=2)

 

>>> dir1 = {}

>>> dir1

{}

>>> d1 = dict(((1,'a'),(2,'b')))

>>> d1

{1: 'a', 2: 'b'}

 

>>> d2 = dict(a = 'aa',b='bb')

>>> d2

{'a': 'aa', 'b': 'bb'}

 

>>> d2['a']='aaaaa'

>>> d2

{'a': 'aaaaa', 'b': 'bb'}

>>> d2['3']='ccccc'

>>> d2

{'a': 'aaaaa', 'b': 'bb', '3': 'ccccc'}

 

4.字典的内嵌方法fromkeys(...)创建并且访问新的字典。

函数有两个参数,第一个是键,第二个是键值,没有第二个参数则默认为None.

 

>>> dict1 = {}

>>> dict.fromkeys((1,2,3))

{1: None, 2: None, 3: None}

默认参数为None

>>>dict1.fromkeys((1,2,3),'Number')

{1: 'Number', 2: 'Number', 3: 'Number'}

不要试图这么做:

>>>dict1.fromkeys((1,2,3),('one','two','three'))

{1: ('one', 'two', 'three'), 2: ('one','two',
ada8
'three'), 3: ('one', 'two', 'three')}

它会把第二个参数作为一个整体赋值给每个元素的值。

 

不要试图修改字典。它会重新创建新的字典。

>>> dict1

{}

>>> dict1.fromkeys((1,2,3))

{1: None, 2: None, 3: None}

>>> dict1

{}

>>> dict1 = dict1.fromkeys((1,2,3),'a')

>>> dict1

{1: 'a', 2: 'a', 3: 'a'}

>>> dict1.fromkeys((1,3),'aaa')

{1: 'aaa', 3: 'aaa'}

5.keys(),values(),items()

keys()返回字典的引用。

values()返回字典的键值。

items()返回字典的每一项。

>>>dict1=dict1.fromkeys(range(8),'good')

>>> dict1

{0: 'good', 1: 'good', 2: 'good', 3:'good', 4: 'good', 5: 'good', 6: 'good', 7: 'good'}

>>> for eachkey in dict1.keys():

         print(eachkey)

 

        

0

1

2

3

4

5

6

7

 

>>> for eachvalue indict1.values():

         print(eachvalue)

 

        

good

good

good

good

good

good

good

good

>>> for items in dict1.items():

         print(items)

 

        

(0, 'good')

(1, 'good')

(2, 'good')

(3, 'good')

(4, 'good')

(5, 'good')

(6, 'good')

(7, 'good')

 

 

6.get()方法获取键值

>>>#索引不存在的键会出错

>>> print(dict1[32])

Traceback (most recent call last):

 File "<pyshell#35>", line 1, in <module>

   print(dict1[32])

KeyError: 32

用户体验不是很好。

用get()方法比较好,如果试图访问字典不存在的键,不会报错。

 

>>> dict1.get(32)

>>> print(dict1.get(32))

None

其实此时也返回了值,值为None.

 

我们可以在返回不存在的键的时候可以设置打印出来的值,访问存在的值时可以正常打印其值。

>>> print(dict1.get(8))

None

>>> dict1.get(8,'没有此值')

'没有此值'

>>> dict1.get(5,'没有此值')

'good'

 

可以实现用in/not in 来检查键是否存在于字典中。

>>> 7 in dict1

True

>>> 8 in dict1

False

 

7.copy()方法

>>> #copy 浅拷贝

>>> #不要把赋值当成浅拷贝

>>>

>>> a ={1:'a',2:'b',3:'c'}

>>> b = a.copy()

>>> c = a

>>> a

{1: 'a', 2: 'b', 3: 'c'}

>>> b

{1: 'a', 2: 'b', 3: 'c'}

>>> c

{1: 'a', 2: 'b', 3: 'c'}

>>>

>>> id(a)

49073896

>>> id(b)

49073824

>>> id(c)

49073896

>>> #此时a c 是用一个Id,他们只是不同的标签指向了同一个内存空间,没有实现真正的拷贝

>>> #而a,b是不同的id,它们是不同的字典,是真正拷贝过来的,处于不同的内存空间。

 

8.pop()  popitem()方法。

>>> a

{1: 'a', 2: 'b', 3: 'c'}

>>>a.pop(2)

'b'

返回的是键值

此时a 中剩下两个元素:{1: 'a', 3: 'c'}

 

>>> a

{1: 'a', 2: 'b', 3: 'c'}

>>>a.popitem()

(3, 'c')

 

返回的是一项

>>> a

{1: 'a', 2: 'b'}

>>>a.popitem()

(2, 'b')

>>> a

{1: 'a'}

 

9.setdefault()和update()来更新字典。

setdefault()增添:键自定义、键值为None的新项。

update()参数为字典。将参数的项添加到原字典中。

>>> a

{1: 'a'}

>>> a.setdefault('000')

>>> a

{1: 'a', '000': None}

>>> a.setdefault('a')

>>> a

{1: 'a', '000': None, 'a': None}

 

>>>b = {'小白':'dog'}

>>>a.update(b)

>>>

>>> a

{1: 'a', '000': None, 'a': None, '小白': 'dog'}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息