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/python

dict = {'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/python

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

print "dict['Name']: ", dict['Name'];

5相关函数

Python includes following dictionary functions

SN Function with Description
1 cmp(dict1, dict2)
Compares elements of both dict.
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
3 str(dict)
Produces a printable string representation of a dictionary
4 type(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

SN Methods with Description
1 dict.clear()
Removes all elements of dictionary dict
2 dict.copy()
Returns a shallow copy of dictionary dict
2 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value .
3 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
4 dict.has_key(key)
Returns true if key in dictionary dict , false otherwise
5 dict.items()
Returns a list of dict 's (key, value) tuple pairs
6 dict.keys()
Returns list of dictionary dict's keys
7 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict
8 dict.update(dict2)
Adds dictionary dict2 's key-values pairs to dict
9 dict.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认为数字是不可变的。

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

Python Dictionary相关推荐

  1. Simple Python Dictionary :)

    摘自 http://github.com/panweizeng/home/blob/master/code/python/dict/dict.py 支持简单的Ch to En 和En to Ch我把它 ...

  2. [转载] Python Dictionary用法小结

    参考链接: Python字典dictionary | fromkeys()方法 一.Dictionary字典基本语法和操作 实例:dict = {'Alice': '2341', 'Beth': '9 ...

  3. Python Dictionary 字典

    字典反转(reverse/inverse dictionary/mapping) Python字典反转就是将原字典的key作为value,而原来的value作为key,得到新的一个字典.如: 原字典为 ...

  4. python dictionary排序_对Python的字典进行排序

    我们知道Python的内置dictionary数据类型是无序的,通过key来获取对应的value.可是有时我们需要对dictionary中 的item进行排序输出,可能根据key,也可能根据value ...

  5. python dictionary的遍历

    d = {'x':1, 'y':3, 'z':2} for k in d:     print d[k] 直接遍历k in d的话,遍历的是dictionary的keys. 2 字典的键可以是任何不可 ...

  6. python dictionary怎么用_python Dictionary字典使用

    一.dictionary数据类型的结构是:{key1:value1, key2:value2, ...},即键值对.字典的健必须是不可更改的类型,如字符串.数字.元祖等:而值则可以是任意的数据类型,而 ...

  7. How to create a Python dictionary with double quotes as default quote format?

    couples = [['jack', 'ilena'], ['arun', 'maya'], ['hari', 'aradhana'], ['bill', 'samantha']] pairs = ...

  8. python深度神经网络量化_基于Python建立深度神经网络!你学会了嘛?

    原标题:基于Python建立深度神经网络!你学会了嘛? 图1 神经网络构造的例子(符号说明:上标[l]表示与第l层:上标(i)表示第i个例子:下标i表示矢量第i项) 单层神经网络 图2 单层神经网络示 ...

  9. Python之xml文件处理(一)——使用ElementTree遍历xml

    2019独角兽企业重金招聘Python工程师标准>>> 发现python上有关xml的实现方法还是蛮多的,第三方的框架也不少,但是其中没有像dom4j那样名声响亮的框架.所以,还是中 ...

最新文章

  1. 2022-2028年中国帘子布行业市场研究及前瞻分析报告
  2. UC阿里鱼卡全网免流活动正在进行
  3. CSS 7:网页布局(传统布局,flex布局,布局套路)
  4. asp.net页面处理过程文章整理
  5. 聊聊storm的PartialKeyGrouping
  6. Hibernate之映射
  7. 单独组件_阿里P8年薪百万大牛-教你打造一个Android组件化开发框架
  8. Java面向对象知识总结
  9. java面向对象_谈谈Java的面向对象
  10. VMware虚拟机克隆或复制linux后无法上网的解决方案
  11. 【bzoj1614】[Usaco2007 Jan]Telephone Lines架设电话线 二分+SPFA
  12. 杀毒软件 对应的进程名称
  13. PID算法理解和代码以及PID调参
  14. windows通过cmd命令行下载FTP中文件的几种方式
  15. 编译原理:什么是编译程序?
  16. php 新手二维码生成
  17. 动圈话筒,电容话筒,驻极体话筒的区别
  18. 从头到尾彻底理解傅里叶变换算法
  19. springboot项目打jar包跳过单元测试test
  20. 2022危险化学品经营单位安全管理人员考试试题及答案

热门文章

  1. 贴福字、集五福、沾福气!这才是“中国福“的最优雅打开姿势
  2. 开源软件安装及版本控制
  3. moonlight鼠标延迟解决
  4. OpenDaylight(Oxygen)安装feature出现错误的解决方案
  5. c++第八周【任务1-3】实现复数类中的运算符重载
  6. 饭后时间(四)---SSD先验框的尺寸及计算源码(含代码ssd_anchor.py)
  7. 【FXCG】英国去年12月通胀创近30年最高纪录
  8. word 2010 尾注 尾注序号 连续尾注 尾注分隔符 删除(from 163 blog)
  9. JPA基础(二)之实现一个简单 JPA 例子
  10. 小米服务组件是什么东西_小米10至尊纪念版都有哪些绝活 | 小米推出的服务超大杯又是什么?...