博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python中字典操作
阅读量:4052 次
发布时间:2019-05-25

本文共 5379 字,大约阅读时间需要 17 分钟。

1基本定义

Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as follows:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

 

2 往dictionary中添加新元素或者修改

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print ("dict['Age']: ", dict['Age']);
print ("dict['School']: ", dict['School']);

 

3 删除元素

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict
del dict ;        # delete entire dictionary

 

4两点这样:

(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins.

Example:

#!/usr/bin/pythondict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};print "dict['Name']: ", dict['Name'];

This will produce following result:

dict['Name']:  Manni

(b) Keys must be immutable. Which means you can use strings, numbers, or tuples as dictionary keys but something like ['key'] is not allowed.

Example:

#!/usr/bin/pythondict = {['Name']: 'Zara', 'Age': 7};print "dict['Name']: ", dict['Name'];

 

5相关函数

Python includes following dictionary functions

SN Function with Description
1  
Compares elements of both dict.
2  
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
3  
Produces a printable string representation of a dictionary
4  
Returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.

Python includes following dictionary methods

SN Methods with Description
1  
Removes all elements of dictionary dict
2  
Returns a shallow copy of dictionary dict
2  
Create a new dictionary with keys from seq and values set to value .
3  
For key key, returns value or default if key not in dictionary
4  
Returns true if key in dictionary dict , false otherwise
5  
Returns a list of dict 's (key, value) tuple pairs
6  
Returns list of dictionary dict's keys
7  
Similar to get(), but will set dict[key]=default if key is not already in dict
8  
Adds dictionary dict2 's key-values pairs to dict
9  
Returns list of dictionary dict2 's values

 

补充:

使用不存在的key访问value会产生keyerror exception。可以通过get(key[,obj])来访问,如果不存在则会返回None。并且也可以在不存在的情况下指定默认值。

 

popitem

popitem 弹出随机的项
>>> d ={'title':'Python Web Site','url':'http://www.python.org','spam':0}
>>> d.popitem()
('url', 'http://www.python.org')
>>> d
{'spam': 0, 'title': 'Python Web Site'}

 

 

Python中的引用:

Python stores any piece of data in an object, and variables are merely references to an object;they are names for a particular spot in the computer's memory.All objects have a unique identity number,a type and a value.

 

Because varaibles just reference objects, a change in a mutable object's value is visible to all variables referencing that object:

>>> a=[1,2]

>>> b=a
>>> a[1]=8
>>> b
[1, 8]
>>> a = 3
>>> b=a
>>> b
3
>>>

 

each object also contains a reference count that tells how many variables are currently referencing that object.If the reference count reaches zero, python's garbage collector destroys the object and reclaims the memory it was using.

 

sys.getrefcount(obj): return the reference count for the given object.

 

Note: del 并不是删除一个对象而是一个变量,只有当这个变量是最后一个refrence 该对象时,python才删除该对象。

 

>>> a=[1,2]

>>> b=a
>>> a[1]=8
>>> b
[1, 8]
>>> a = 3
>>> b=a
>>> b
3
>>> 删除了a,但是a所指的对象并没有删除。

 

>>> a = [1,2,3]

>>> del a
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

 

 

对象之间的拷贝:

Python有两种拷贝:浅拷贝和深拷贝。

 

Shallow copies:浅拷贝

定义: A shallow copy of a list or other container object  makes a copy of the object itself but create references to the objects contained by the list.

 

使用copy(obj)进行浅拷贝。

 

>>> test = [1,2,3]

>>> ref = test[:]
>>> ref is test
False
>>> ref == test
True

 

A shallow copy of the parent list would contain a reference to the child list,not a seperate copy.As a result,changes to the inner list would be visible from both copies of the parent list.

>>> myAccount = [100,['checking','saving']]

>>> youCount = myAcount
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'myAcount' is not defined
>>> youCount = myAcount[:]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'myAcount' is not defined
>>> youCount = myAccount
>>> myAccount[1].remove('saving')
>>> myAccount 
[100, ['checking']]
>>> youCount 
[100, ['checking']]
>>>

 

深拷贝:定义

A deep copy makes a copy of the container object and recursively makes copies of all the children objects.using copy.deepcopy(obj) to do deep copy.

 

 

>>> myAccount = [100,['test1','test2']]

>>> yourAccount = copy.deepcopy(myAccount)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'copy' is not defined
>>> import copy
>>> yourAccount = copy.deepcopy(myAccount)
>>> myAccount[1].remove('test2')
>>> myAccount 
[100, ['test1']]
>>> yourAccount 
[100, ['test1', 'test2']]

 

但是有点需要特别提醒的,如果对象本身是不可变的,那么浅拷贝时也会产生两个值, 看个例子:

>>> aList =[1,2]

>>> bList = aList[:]
>>> bList
[1, 2]
>>> aList
[1, 2]
>>> aList[1]=111
>>> aList
[1, 111]
>>> bList
[1, 2]

 

原因在于python认为数字是不可变的。

可变类型: 列表,字典

不可变类型:数字,字符串,元组

 

转载地址:http://vnxci.baihongyu.com/

你可能感兴趣的文章
java LinkedList与ArrayList迭代器遍历和for遍历对比
查看>>
drat中构造方法
查看>>
JavaScript的一些基础-数据类型
查看>>
转载一个webview开车指南以及实际项目中的使用
查看>>
ReactNative使用Redux例子
查看>>
Promise的基本使用
查看>>
coursesa课程 Python 3 programming 统计文件有多少单词
查看>>
coursesa课程 Python 3 programming 输出每一行句子的第三个单词
查看>>
Returning a value from a function
查看>>
course_2_assessment_6
查看>>
coursesa课程 Python 3 programming course_2_assessment_7 多参数函数练习题
查看>>
coursesa课程 Python 3 programming course_2_assessment_8 sorted练习题
查看>>
在unity中建立最小的shader(Minimal Shader)
查看>>
1.3 Debugging of Shaders (调试着色器)
查看>>
关于phpcms中模块_tag.class.php中的pc_tag()方法的含义
查看>>
vsftp 配置具有匿名登录也有系统用户登录,系统用户有管理权限,匿名只有下载权限。
查看>>
linux安装usb wifi接收器
查看>>
多线程使用随机函数需要注意的一点
查看>>
getpeername,getsockname
查看>>
关于对象赋值及返回临时对象过程中的构造与析构
查看>>