python中字典操作

来源:互联网 发布:淘宝解id锁解开率高吗 编辑:程序博客网 时间:2024/05/16 19:07

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

SNFunction with Description1cmp(dict1, dict2) 
Compares elements of both dict.2len(dict) 
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.3str(dict) 
Produces a printable string representation of a dictionary4type(variable) 
Returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type.

Python includes following dictionary methods

SNMethods with Description1dict.clear() 
Removes all elements of dictionary dict2dict.copy() 
Returns a shallow copy of dictionary dict2dict.fromkeys() 
Create a new dictionary with keys from seq and values set to value .3dict.get(key, default=None) 
For key key, returns value or default if key not in dictionary4dict.has_key(key) 
Returns true if key in dictionary dict , false otherwise5dict.items() 
Returns a list of dict 's (key, value) tuple pairs6dict.keys() 
Returns list of dictionary dict's keys7dict.setdefault(key, default=None) 
Similar to get(), but will set dict[key]=default if key is not already in dict8dict.update(dict2) 
Adds dictionary dict2 's key-values pairs to dict9dict.values() 
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认为数字是不可变的。

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