自学Python2.4-基本数据类型-字典dict(objct)

Python dict方法总结 

一、字典介绍

1.字典概述

①字典是python中唯一内建的映射类型。又称关联数组或散列
②映射类型对象里哈希值(键,key)和指向的对象(值,value)是一对多的的关系,通常被认为是可变的哈希表
③字典对象是可变的,它是一个容器类型,能存储任意个数的Python对象,其中也可包括其他容器类型。
④字典通过键实现元素存取,可变类型容器,长度可变,异构,嵌套

2.字典类型与序列类型的区别:

①存取和访问数据的方式不同。
②序列类型只用数字类型的键(从序列的开始按数值顺序索引);
③映射类型可以用其他对象类型作键(如:数字、字符串、元祖,一般用字符串作键),和序列类型的键不同,映射类型的键直接或间接地和存储数据值相关联。
④映射类型中的数据是无序排列的。这和序列类型是不一样的,序列类型是以数值序排列的。
⑤映射类型用键直接“映射”到值。

二、字典的基本操作

1、创建字典

   {key1:value1,key2:value2, .....}

   {}   表示空字典

   {‘x’:32,‘y’:[1,2,3]}

特点:
1、键与值用冒号“:”分开;
2、项与项用逗号“,”分开;
3、字典中的键必须是唯一的,而值可以不唯一。

建议:

如果字典中的值为数字,最好使用字符串数字形式,如:'age':'26′ 而不用 ‘age':26

2、如何访问字典中的值?
     dict[key] 形式返回键key对应的值value,如果key不在字典中会引发一个KeyError。

dict={'x':32,'y':[1,2,3,4,]}
result=dict['x']   #取值的时候按键key取值
print(result)

输出32

dict={'x':32,'y':[1,2,3,4,]}
result=dict['y'][3:]   #按键key取值,里面列表索引为3的值
print(result)

输出4

3、如何检查key是否在字典中?

①has_key()方法 形如:dict.haskey(‘name') 有–>True,无–>False
②in 、not in   形如:'name' in dict      有–>True,无–>False

4、如何更新字典?

①添加一个数据项(新元素)或键值对
 dict[new_key] = value 形式添加一个项

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['sex'] = 'female'
print(dict)

出{'Name': 'Zara', 'Age': 7, 'Class': 'First', 'sex': 'female'}

②更新一个数据项(元素)或键值对
 dict[old_key] = new_value

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8
dict['School'] = "DPS School"
print(dict['Age'],dict['School'])
print(dict)

输出

8 DPS School
{'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'DPS School'}

③删除一个数据项(元素)或键值对
 del  dict[key] 删除键key的项 / del dict 删除整个字典
 del  dict  删除字典
 dict.pop(key) 删除键key的项并返回key对应的 value值
 dict.clear() 清空字典所有条目

四、映射类型操作符

标准类型操作符(+,-,*,<,>,<=,>=,==,!=,and,or, not)

a、字典不支持拼接和重复操作符(+,*)
b、字典的比较操作
先比较字典的长度也就是字典的元素个数
      键比较
      值比较

五、映射相关的函数

1、len() 计算字典元素个数,即键的总数
2、hash() 返回对象的哈希值,可以用来判断一个对象能否用来作为字典的键
3、dict() 工厂函数,用来创建字典
4、cmp(dict1, dict2):比较两个字典元素
5、str(dict):输出字典可打印的字符串表示
6、type(variable):返回输入的变量类型,如果变量是字典就返回字典类型

六、字典的方法

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
字典源码

1. clear(self)清除字典中所有的项

d={}
d['name']='carlos'
d['age']='26'
print(d)
result=d.clear()
print(result)

输出

{'name': 'carlos', 'age': '26'}
None

2. copy(self) 返回一个具有相同键值对的新字典(shallow copy浅复制,因为值本身就是相同的,不是副本)

dict1={'username':'admin','machine':['foo','bar','baz']}
dict2=dict1.copy()
print(dict1)
print(dict2)
dict2['username']='carlos'
print(dict1)
print(dict2)
dict2['machine'].remove('bar')
print(dict1)
print(dict2)

输出

{'username': 'admin', 'machine': ['foo', 'bar', 'baz']}
{'username': 'admin', 'machine': ['foo', 'bar', 'baz']}
{'username': 'admin', 'machine': ['foo', 'bar', 'baz']}
{'username': 'carlos', 'machine': ['foo', 'bar', 'baz']}
{'username': 'admin', 'machine': ['foo', 'baz']}
{'username': 'carlos', 'machine': ['foo', 'baz']}

①浅复制shallow copy ,如上,当在副本中替换值的时候原始字典不受影响,但是如果修改了某个值,原始的字典也会随之改变。

②深复制deep copy,复制其包含的所有值。

from copy import deepcopy
dict={'username':'admin','machine':['foo','bar','baz']}
dict1=dict.copy()
dict2=deepcopy(dict)
print(dict1)
print(dict2)
dict['machine'].remove('bar')
print(dict1)
print(dict2)

输出

{'username': 'admin', 'machine': ['foo', 'bar', 'baz']}
{'username': 'admin', 'machine': ['foo', 'bar', 'baz']}
{'username': 'admin', 'machine': ['foo', 'baz']}
{'username': 'admin', 'machine': ['foo', 'bar', 'baz']}

3. fromkeys(*args, **kwargs) 使给定的键建立一个新的字典,每个键对应默认的值都是none

dict1={}
dict2=dict1.fromkeys(['name','age'])
print(dict1)
print(dict2)

输出{}

       {'name': None, 'age': None}

4. get(self, k, d=None) 更宽松的访问字典项的方法

一般如果试图访问字典中不存在的项会报错,但使用get就不会,而是得到none值。

dict={'username':'admin','machine':['foo','bar','baz']}
result=dict.get('machine')
print(result)

输出['foo', 'bar', 'baz']

dict={'username':'admin','machine':['foo','bar','baz']}
result=dict.get('age')
print(result)

输出None

5. items(self)  将字典所有的项以列表方式返回,列表中的每一项都表示(键,值)对的形式,返回时无特定的次序

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
result=dict.items()
print(result)

输出 dict_items([('title', 'Python Web Site'), ('url', 'http://www.python.org'), ('spam', 0)]) 

  iteritems 方法大致一致,但是返回一个迭代器对象而不是列表。

6. keys(self) 将字典中键以列表方式返回。

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
result=dict.keys()
print(result)

输出dict_keys(['title', 'url', 'spam'])

   iterkeys 将字典中键以列表方式返回,但是返回一个针对键的迭代器。   

7.  pop(self, k, d=None) 获得对应给定键的值,然后将这个键值对从字典中移除。

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
result=dict.pop('url')
print(result)
print(dict)

输出

http://www.python.org
{'title': 'Python Web Site', 'spam': 0}

   popitem(self) 获得随机的项,然后将这个项对从字典中移除。

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
result=dict.popitem()
print(result)
print(dict)

输出

('spam', 0)
{'title': 'Python Web Site', 'url': 'http://www.python.org'}

8.setdefault(self, k, d=None) 获得与给定键值相关联的值,当键不存在的时候,返回默认值none且相应的更新字典,当键存在的时候,返回对应的值,不改变字典。

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
result=dict.setdefault('url')
print(result)
print(dict)

输出

http://www.python.org
{'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
result=dict.setdefault('name')
print(result)
print(dict)

输出

None
{'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0, 'name': None}

9. update(self, E=None, **F) 利用一个字典项更新另外一个字典

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
print(dict)
dict1={'title':'Python Language Site'}
dict.update(dict1)
print(dict)

输出

{'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}
{'title': 'Python Language Site', 'url': 'http://www.python.org', 'spam': 0}

10. values(self)  以列表的形式返回字典中的值,返回值的列表中可以包含重复的元素

     itervalues返回值的迭代器

dict={'title':'Python Web Site','url':'http://www.python.org','spam':0}
print(dict)
result=dict.values()
print(result)

输出

{'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}
dict_values(['Python Web Site', 'http://www.python.org', 0])

七、字典键的特性  

①不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住

dict={'name':'carlos','age':'26','name':'alex'}
print(dict)

输出{'name': 'alex', 'age': '26'}

②键必须不可变,所以可以用数,字符串或元组充当,所以用列表就不行

③自动添加,若字典不存在,也可以为它赋值,字典就会建立新的项

八、字典的遍历

1、遍历字典的key(键)

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
for key in dict.keys():
     print(key)

输出

Name
Age
Class 

2、遍历字典的value(值)

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
for value in dict.values():
     print(value)

输出

Zara
7
First

3、遍历字典的项(元素)

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
for item in dict.items():
     print(item)

输出

('Name', 'Zara')
('Age', 7)
('Class', 'First')   

posted on 2017-08-22 10:14  CARLOS_KONG  阅读(478)  评论(0编辑  收藏  举报

导航