python--字典dict

字典由多个键与其对应的值构成的对组成,是另一种可变容器模型,且可存储任意类型对象。字典的每个键值用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中。

注:字典中的键是唯一的(其他类型的映射也是如此),而值不是唯一的。

字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿.即,我们把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的,字典中的键/值对是没有顺序的(字典是无序的)。如果想要一个特定的顺序,那么应该在使用前自己对它们排序。字典是dict类的实例/对象。

字典是python中唯一的内建映射类型

1.dict 函数

使用dict 函数,通过其他映射(其他字典或键-值)这样的序列对建立字典

items = [("name","zhangsan"),("age",28),("job","educator")]
D = dict(items)
print (D)
print (type(D))

2. 字典的格式化字符串

一个电话本为例子的字典代码(引用格式化字符串)

phonebook = {
"zhangsan":{
"phone":"01012345",
"addr":"tianhedong 32 hao",
},
"lisi":{
"phone":"02023456",
"addr":"huangpunan 54 hao",
},
"zhaowu":{
"phone":"03034567",
"addr":"tianhebei 17 hao",
},
"xiesen":{
"phone":"06054321",
"addr":"tianhexi 12 hao",
},
} labels ={
"phone":"phone numbers",
"addr":"address"
} name = input ("please input your name:") if "request" == "p" :key = "phone"
if "request" == "a" :key = "addr"
if name in phonebook :
print ("%s's %s is %s." %(name, labels[key], phonebook[name][key]))

字典的方法

1. clear

clear 清除字典的所有项.类似list.sort ,无返回值

D = {}
D["name"] = "xieshengsen"
D["age"] = 25 print (D) returned_value = D.clear() print (D)
print (returned_value)

2. copy

copy 返回一个具有相同键值对的新字典(浅复制)

Q = {"username":"admin","machines":["foo","bar","baz"]}
QQ = Q.copy()
print (Q)
print (QQ) QQ["username"] = "Administrator"
QQ["machines"].remove("bar") print(Q)
print(QQ)

深复制

form copy import deepcopy

import copy

d = {}
d["names"] = ["hello","world"] print (d) dd = copy.copy(d)
dc = copy.deepcopy(d)
d["names"].append("haha") print (d)
print (dd)
print(dc)

3. fromkeys

fromkeys 使用给定的键建立新的字典,每个键默认对应的值为none

print({}.fromkeys(["name","age"])) # none 作为默认值

print(dict.fromkeys(["name","age"]),"(unknown)") # 修改unknown 为默认值

4. get

get 更宽松的访问字典项的方法(一般来说,如果访问字典中不存在的项时会出错,使用get访问不会出现错误)

AA = {}
# print (AA["name"]) # 出现错误 print (AA.get("name")) # 键值不存在,输出结果None AA["name"]= "xieshengsen"
print (AA.get("name"))

5. items 和iteritems

items 方法将所有的字典项以列表方式返回,这些列表项中的每一项都是来自(键-值)。但是项在返回时并没有特殊的顺序。

II = {"title": "python web site","url":"https://www.python.org","spam":0}
print (II.items())

iteritems 会返回一个迭代器 而不是列表(python3 已经没有iteritems 这个方法)

6. keys 和iterkeys

keys 方法将字典的键以列表形式返回,而iterkeys 则返回针对键的迭代器

7. pop

pop 方法用来获取对应于给定的键的值,然后将这个键-值对从字典中移除

dd = {"hh":1,"yy":2,"vv":3,"gg":4}
print (dd.pop("hh"))
print (dd)

8. popitem

popitem 方法类似于list.pop,后者会弹出列表的最后一个元素。但,popitem弹出随机项,因为字典没有“最后元素”的概念(字典是无序的).

p = {"url":"https://www.python.org/","spam":0,"title":"python web site"}
print (p.popitem())
print (p)

9. setdefault

setdefault 类似于get方法,能够获得与给定键相关联的值,setdefault还能在字典中不含有给定键的情况下设定相应的键值

set = {}
print (set.setdefault("name","N/A"))
print (set) set["name"] = "zhangsan"
print (set.setdefault("name","N/A"))
print (set)

当键不存在时,setdefault 返回默认值并相应的更新字典,如果键存在,返回其相应值,但不改变字典。

10. update

update 方法是利用一个字典项更新另外一个字典.

up = {"color":"red","number":"1234","animal":"Bear","Fruits":"apples"}
da = {"Stationery":"book","food":"milk"}
up.update(da)
print (up)

提供的字典的项会被添加到旧字典中,相同的键会被覆盖

11. values

values 方法以列表的形式返回字典的值(itervalues 返回值的迭代器,python3 没有),与返回值的列表不同的是,返回值列表中可以包含重复的元素。

valu = {}
valu[1]=1
valu[2]=2
valu[3]=3
valu[4]=1
print (valu.values())

字典dict官方解析

class dict(object):
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
"""
def clear(self): # real signature unknown; restored from __doc__
""" D.clear() -> None. Remove all items from D. """
pass def copy(self): # real signature unknown; restored from __doc__
""" D.copy() -> a shallow copy of D """
pass @staticmethod # known case
def fromkeys(*args, **kwargs): # real signature unknown
""" Returns a new dict with keys from iterable and values equal to value. """
pass def get(self, k, d=None): # real signature unknown; restored from __doc__
""" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
pass def items(self): # real signature unknown; restored from __doc__
""" D.items() -> a set-like object providing a view on D's items """
pass def keys(self): # real signature unknown; restored from __doc__
""" D.keys() -> a set-like object providing a view on D's keys """
pass def pop(self, k, d=None): # real signature unknown; restored from __doc__
"""
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
"""
pass def popitem(self): # real signature unknown; restored from __doc__
"""
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
"""
pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
pass def update(self, E=None, **F): # known special case of dict.update
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
"""
pass def values(self): # real signature unknown; restored from __doc__
""" D.values() -> an object providing a view on D's values """
pass def __contains__(self, *args, **kwargs): # real signature unknown
""" True if D has a key k, else False. """
pass def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
# (copied from class doc)
"""
pass def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -> size of D in memory, in bytes """
pass __hash__ = None
上一篇:EntityFramework Code-First 简易教程(四)-------继承策略


下一篇:java动手动脑2