【六】Python基础之数据结构:字典

字典常用操作:索引、新增、删除、【键、值、键值对】、循环、长度

创建字典:

1 2 3

person = {"name": "mr.wu", 'age': 18} 或 person = dict({"name": "mr.wu", 'age': 18})

Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,字典是另 一种可变容器模型,且可存储任意类型对象。具有极快的查找速度。

字典是一种通过名字或者关键字引用的得数据结构,其键可以是数字、字符串、元组,这种结构类型也称之为映射。字典类型是Python中唯一內建的映射类型,基本的操作包括如下:

(1) len() : 返回字典中 键:值对 的数量

(2) d[k] : 返回关键字对应的值;

(3) d[k] = v : 将值关联到键值k上;

(4) del d[k ] :删除键值为k的项;

(5) key in d : 键值key是否在d中,是返回True,否则返回False

举例字典:

1 2 3 4 5 6 7 8 9 10 11

d = { "k1": 18, "k2": True, "k3": ['Su', { 'kk1': 'vv1', 'kk2': 'vv2', 'kk3': (11, 22), } ], "k4": (11, 22, 33, 44) }

1.字典的基本格式:

1

d = {key1 : value1, key2 : value2 }

2.字典的键(key)必须不可变(如:字符串,数字,元组),值(key)可以为任意数据类型

1

d1 = {'Alice': '2341', 9102: 'Bibi', (11,22): '3258'}  # 正确<br>d2 = {['Alice',123]: '2341', True: '9102', {'abc': '123', 'efg': '456'}}  # 错误! 因为列表 布尔值 字典都是可变的,不能作为键(key)

3.字典是无序的,每次执行打印,顺序都会发生改变 

1 2 3 4 5 6 7 8 9 10 11

d3 = {'Alice': '2341', 9102: 'Bibi', (11,22): '3258'} print(d) # 打印结果可能是这样 {'Alice': '2341', 9102: 'Bibi', (11, 22): '3258'} # 也有可能是这样 {(11, 22): '3258', 'Alice': '2341', 9102: 'Bibi'} # 甚至可能是这样 {9102: 'Bibi', 'Alice': '2341', (11, 22): '3258'} ... ...

 4.根据键(key)或值(value)取出对应的值(value)或键(key) & for 循环

  1.返回关键字对应的值: v = d[key] 例(参考举最上方举例字典):  

1

v = d["k1"]  # 取出k1对应的value<br>v1 = d["k3"][1]["kk3"][0]  # 取出kk3对应的value中的11<br><br>print(v, v1)

  2.不可通过切片方式获取键值对,因为字典无序

  3.for循环取key和value 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

d4 = {'Year': 2018, 'Month': 3, 'Day': 18} # 循环所有的key (或这么写:for item in d4.keys():) for item in d4: print(item) 打印结果: Year Month Day # 循环所有的value for item in d4.values(): print(item) 打印结果: 2018 3 18 # 循环所有的key:value for item in d4.keys(): print(item, ':', d4[item]) for k, v in d4.items(): # 用items方法 k接收key ,v接收value   print(k, v)

5.字典的函数&方法

1.函数(3):

  1.str(dict)      #输出字典可以打印的字符串表示

1 2 3 4

d6 = {'Year': 2018, 'Month': 3, 'Day': 18} content = str(d6) print(content) 打印结果:{'Year': 2018, 'Month': 3, 'Day': 18}

  2.len(dict)      #计算字典内元素的个人,即键的总数

1 2 3 4

d7 = {'Year': 2018, 'Month': 3, 'Day': 18} count = len(d7) print(count) 打印结果:3

  3.type(variable)   #返回输入的变量类型,如果变量类型是字典就返回字典

1 2 3 4

d8 = {'Year': 2018, 'Month': 3, 'Day': 18} ty = type(d8) print(ty) 打印结果:<class 'dict'>

2.方法()

  1.删除 

1 2 3 4 5 6

d4 = {'Alice': '2341', 9102: 'Bibi', (11,22): '3258'} del d4[9102] # 删除元素 9102:Bibi print(d4) # 打印结果:{'Alice': '2341', (11, 22): '3258'} d4.clear()    # 清空字典 print(d4) # 打印结果:{} del d4      # 删除字典

  2.items()方法,循环获取key和value

1 2 3

d4 = {'Year': 2018, 'Month': 3, 'Day': 18} for k, v in d4.items(): # 用items方法 k接收key ,v接收value print(k, v)

  3.keys()方法,循环获取所有key

1 2 3

d4 = {'Year': 2018, 'Month': 3, 'Day': 18} for item in d4.keys(): # 循环所有的key print(item)

  4.values()方法,循环获取所有value

1 2 3

d4 = {'Year': 2018, 'Month': 3, 'Day': 18} for item in d4.values(): # 循环所有的values print(item)

  5.copy(浅拷贝)

1 2 3 4

d4 = {'Year': 2018, 'Month': 3, 'Day': 18} dict2 = d4.copy() print ("新复制的字典为 : ",dict2)

  6.fromkeys() 创建一个新字典,fromkeys(*args, **kwargs) 以*args中元素做字典的键,**kwargs为字典所有键对应的初始值

1 2 3 4 5 6 7 8 9

new_d = ('Year', 'Month', 'Day') dict1 = dict.fromkeys(new_d) print("新的字典 : %s" % str(dict1)) dict1 = dict.fromkeys(new_d, 8) print("新的字典 : %s" % str(dict1)) 打印结果: 新的字典 : {'Year': None, 'Month': None, 'Day': None} 新的字典 : {'Year': 8, 'Month': 8, 'Day': 8}

  7.get()方法根据key获取值 get(self, k, d=None) 参数:k:待操作的键(key), d:默认为None,在获取键的时候,如果不存在就返回 None 或指定什么就返回什么

1 2 3 4 5 6 7 8 9 10 11 12

d9 = {'Year': 2018, 'Month': 3, 'Day': 18} v = d9.get('Day') print('key存在时:', v) v1 = d9.get('Hour') print('key不存在时:', v1) v2 = d9.get('Hour', 1234) print("key不存在时并指定返回值:", v2) 打印结果: 存在: 18 key不存在时: None key不存在时并指定返回值: 1234

  8.pop()方法删除指定的key,pop(self, k, d=None) 参数: k:待删除的key d:如果待删除的key,则返回None ,或指定什么返回什么  

1 2 3 4 5 6 7 8 9

d9 = {'Year': 2018, 'Month': 3, 'Day': 18} v = d9.pop('Day') print('key存在时:', v) # key存在时: 18 v1 = d9.pop('Hour') print('key不存在时:', v1) # key不存在时报错 v2 = d9.pop('Hour', 1234) print("key不存在时并指定返回值:", v2) # key不存在时并指定返回值: 1234

  9.popitem()方法,随机删除一个键值对

1 2 3

d10 = {'Year': 2018, 'Month': 3, 'Day': 18} v1 = d10.popitem()<br>k, v = d10.popitem() print(v1, k, v) # 打印结果:('Day', 18) Month 3

  10.setdefault 方法,给字典设置(增加)新的键,存在就不设置(获取当前key对应的值),不存在就设置并返回当前key对应的值 setdefault(self, k, d=None) 参数:k:待设置(添加)的key   d:默认为空,可以指定value值

1 2 3

d11 = {'Year': 2018, 'Month': 3, 'Day': 18} v = d11.setdefault('hour', '10') # 如果待加入的key跟字典内重复,则不会添加 print(d11, v) # 打印结果:{'Year': 2018, 'Month': 3, 'Day': 18, 'hour': '10'} 10#

  11.update方法 ,更新字典 update(self, E=None, **F)

1 2 3 4

d12 = {'Year': 2018, 'Month': 3, 'Day': 18} d12.update({'Year': 2019, 'Day': 20, 'Hour': 10}) # 第一种写法 # d12.update(Year=2019, Day=20, Hour=10) # 第二种写法 print(d12) # 打印结果:{'Year': 2019, 'Month': 3, 'Day': 20, 'Hour': 10} # 已存在的key就覆盖,不存在的key就添加进字典

字典内置函数&方法

序号

函数及描述

实例

1

len(dict) 计算字典元素个数,即键的总数。

>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> len(dict) 3

2

str(dict) 输出字典,以可打印的字符串表示。

>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> str(dict) "{'Name': 'Runoob', 'Class': 'First', 'Age': 7}"

3

type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。

>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> type(dict) <class 'dict'>

Python字典内置方法:

序号

函数及描述

1

radiansdict.clear()删除字典内所有元素

2

radiansdict.copy()返回一个字典的浅复制

3

radiansdict.fromkeys()创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值

4

radiansdict.get(key, default=None)返回指定键的值,如果值不在字典中返回default值

5

key in dict如果键在字典dict里返回true,否则返回false

6

radiansdict.items()以列表返回可遍历的(键, 值) 元组数组

7

radiansdict.keys()返回一个迭代器,可以使用 list() 来转换为列表

8

radiansdict.setdefault(key, default=None)和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default

9

radiansdict.update(dict2)把字典dict2的键/值对更新到dict里

10

radiansdict.values()返回一个迭代器,可以使用 list() 来转换为列表

11

pop(key[,default])删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。

12

popitem()随机返回并删除字典中的一对键和值(一般删除末尾对)。

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(S, v=None): # real signature unknown; restored from __doc__
        """
        dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
        v defaults to None.
        """
        pass

    def get(self, k, d=None): # real signature unknown; restored from __doc__
        """ 根据key获取值,d是默认值 """
        """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
        pass

    def has_key(self, k): # real signature unknown; restored from __doc__
        """ 是否有key """
        """ D.has_key(k) -> True if D has a key k, else False """
        return False

    def items(self): # real signature unknown; restored from __doc__
        """ 所有项的列表形式 """
        """ D.items() -> list of D's (key, value) pairs, as 2-tuples """
        return []

    def iteritems(self): # real signature unknown; restored from __doc__
        """ 项可迭代 """
        """ D.iteritems() -> an iterator over the (key, value) items of D """
        pass

    def iterkeys(self): # real signature unknown; restored from __doc__
        """ key可迭代 """
        """ D.iterkeys() -> an iterator over the keys of D """
        pass

    def itervalues(self): # real signature unknown; restored from __doc__
        """ value可迭代 """
        """ D.itervalues() -> an iterator over the values of D """
        pass

    def keys(self): # real signature unknown; restored from __doc__
        """ 所有的key列表 """
        """ D.keys() -> list of D's keys """
        return []

    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__
        """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """
        """ 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
        """ 更新
            {'name':'alex', 'age': 18000}
            [('name','sbsbsb'),]
        """
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
        If E present and lacks .keys() method, 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() -> list of D's values """
        return []

    def viewitems(self): # real signature unknown; restored from __doc__
        """ 所有项,只是将内容保存至view对象中 """
        """ D.viewitems() -> a set-like object providing a view on D's items """
        pass

    def viewkeys(self): # real signature unknown; restored from __doc__
        """ D.viewkeys() -> a set-like object providing a view on D's keys """
        pass

    def viewvalues(self): # real signature unknown; restored from __doc__
        """ D.viewvalues() -> an object providing a view on D's values """
        pass

    def __cmp__(self, y): # real signature unknown; restored from __doc__
        """ x.__cmp__(y) <==> cmp(x,y) """
        pass

    def __contains__(self, k): # real signature unknown; restored from __doc__
        """ D.__contains__(k) -> True if D has a key k, else False """
        return False

    def __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        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): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ D.__sizeof__() -> size of D in memory, in bytes """
        pass

    __hash__ = None

dict
下一篇
举报

扫码关注云+社区

领取腾讯云代金券