Python Dictionary

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

SNFunction with Description
1cmp(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 dictionary
4type(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 Description
1dict.clear()
Removes all elements of dictionary dict
2dict.copy()
Returns a shallow copy of dictionary dict
2dict.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 dictionary
4dict.has_key(key)
Returns true if key in dictionary dict , false otherwise
5dict.items()
Returns a list of dict 's (key, value) tuple pairs
6dict.keys()
Returns list of dictionary dict's keys
7dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict
8dict.update(dict2)
Adds dictionary dict2 's key-values pairs to dict
9dict.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字典是一种无序的数据结构,用于存储键值对。它可以通过大括号{}来创建,也可以使用dict()函数来创建。\[2\]例如,可以使用以下代码创建一个字典: ```python my_dict = {'name': 'John', 'age': 25, 'city': 'New York'} ``` 或者可以使用以下代码创建一个字典: ```python my_dict = dict(name='John', age=25, city='New York') ``` 可以使用键来访问字典中的值,例如`my_dict\['name'\]`将返回'John'。\[3\]还可以使用循环来遍历字典的键和值,例如: ```python for key in my_dict: print(key, my_dict\[key\]) for value in my_dict.values(): print(value) ``` 这将分别打印出字典的键和对应的值。\[1\]此外,还可以使用其他方法来增加、更新和删除字典中的元素,以及对字典进行排序和使用其他字典函数和方法进行操作。 #### 引用[.reference_title] - *1* *3* [Python中的字典(Dictionary)](https://blog.csdn.net/smarten57/article/details/130595183)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Python基础学习之字典(Dictionary)](https://blog.csdn.net/u010435091/article/details/102764295)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惹不起的程咬金

来都来了,不赏点银子么

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值