---
title: "菜鸟也来学python 笔记5 - python字典"
author: "ay_guobo"
date: "2011-10-11T22:15:25Z"
tags: []
categories: ["编程语言"]
slug: "python-5-python"
draft: false
lastmod: "2011-10-11T22:15:25Z"
id: 1190099
url: "https://GUOBO.iteye.com/blog/1190099"
---

目前已经学习了字符串，列表和序列了。

下面的是字典类型~

01 ### 第一个程序是在Python Shell - 3.2下编译，得到的结果是正确的。###  
02   
03 &gt;&gt;&gt; dict = {'mother':'妈妈','father':'爸爸','son':'儿子'}  
04 &gt;&gt;&gt; print (dict)  
05 {'son': '儿子', 'father': '爸爸', 'mother': '妈妈'}  
06   
07 ### 第二个是在Spyder下编译，结果就不正确，怎么回事呢？###  
08   
09 # -\*- coding: utf-8 -\*-  
10 """  
11 Created on Tue Oct 11 22:00:43 2011  
12   
13 @author: guobo  
14 """  
15 dict = {'mother':'妈妈','father':'爸爸','son':'儿子'}  
16 print dict  
17   
18 {'son': '\\xe5\\x84\\xbf\\xe5\\xad\\x90', 'father': '\\xe7\\x88\\xb8\\xe7\\x88\\xb8', 'mother': '\\xe5\\xa6\\x88\\xe5\\xa6\\x88'}  
19   
20 总之大家就看正确的吧，字典就那么个意思，带索引的，而且是索引可以是任意类型的。

也可以定义一个空字典

```
>>> type(dict1)
<class 'dict'>
>>> 
```

 

```
>>> dict1['one'] = 'father'
>>> dict1['two'] = 'mother'
>>> dict1['three'] = 'son'
>>> print (dict1)
{'three': 'son', 'two': 'mother', 'one': 'father'}
>>> 
```

 这就是随后追加的字典元素。

字典的delete操作

```
>>> inventory = {'apples': 430, 'bananas': 312,'oranges': 525, 'pears': 217}
>>> print (inventory)
{'pears': 217, 'apples': 430, 'oranges': 525, 'bananas': 312}
>>> del inventory['pears']
>>> print (inventory)
{'apples': 430, 'oranges': 525, 'bananas': 312}
>>> 
```

 

如果要想清空字典呢？就用clear方法

下面研究一下字典的别名和拷贝的问题

 

01 # -\*- coding: utf-8 -\*-  
02 """  
03 Created on Tue Oct 11 22:00:43 2011  
04   
05 @author: guobo  
06 """  
07   
08 inventory\_A = {'apples': 430, 'bananas': 312,'oranges': 525, 'pears': 217}  
09 inventory\_B = inventory\_A  
10 copy = inventory\_A.copy()  
11   
12 inventory\_B\['apples'] = 250  
13 print (inventory\_A)  
14 print (inventory\_B)  
15 print id(inventory\_A)  
16 print id(inventory\_B)  
17   
18 copy\['apples'] = 100  
19 print (copy)  
20 print id(copy)  
21 print (inventory\_A)  
22 print (inventory\_B)  
23   
24 {'pears': 217, 'apples': 250, 'oranges': 525, 'bananas': 312}  
25 {'pears': 217, 'apples': 250, 'oranges': 525, 'bananas': 312}  
26 30709632  
27 30709632  
28 {'oranges': 525, 'apples': 100, 'pears': 217, 'bananas': 312}  
29 98204672  
30 {'pears': 217, 'apples': 250, 'oranges': 525, 'bananas': 312}  
31 {'pears': 217, 'apples': 250, 'oranges': 525, 'bananas': 312}

 

统计字符串