【python学习笔记】字典

1.字典的含义

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

② python的字典为键值对,有些地方称为hash,有些地方称之为关系数组

③ 映射类型区别于序列类型,序列类型以数组的方式进行存储,通过索引的方式获取相对应位置的值,一般索引与对应位置存储的数据毫无关系

2.创建和访问字典

① 空字典

>>> empty = {}
>>> type(empty)
<class 'dict'>

② 直接创建字典

>>> dic = {'x':'hello','y':'world'}
>>> type(dic)
<class 'dict'>
>>> 

③ 用dict()函数创建字典

>>> dict1 = dict((('F',70),('G',80),('H',90)))
>>> dict1
{'F': 70, 'G': 80, 'H': 90}
>>> a = dict(one=1,two=2,three=3)
>>> a
{'one': 1, 'two': 2, 'three': 3}
>>> b = {'one':1,'two':2,'three':3}
>>> b
{'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one','two','three'],[1,2,3]))
>>> c
{'one': 1, 'two': 2, 'three': 3}
>>> d = dict([('one',1),('two',2),('three',3)])
>>> d
{'one': 1, 'two': 2, 'three': 3}
>>> e = dict({'one':1,'two':2,'three':3})
>>> e
{'one': 1, 'two': 2, 'three': 3}
>>> a == b == c == d == e 
True
>>> 

④ 直接给字典赋值进行创建,也可以修改值

>>> dict1 = {}
>>> dict1['one'] = 1
>>> dict1['two'] = 2
>>> dict1['three'] = 3
>>> dict1
{'one': 1, 'two': 2, 'three': 3}
>>> 
>>> dict1 = {'one': 1, 'two': 2, 'three': 3}
>>> dict1['one'] = 3
>>> dict1
{'one': 3, 'two': 2, 'three': 3}
>>> dict1['four'] = 4
>>> dict1
{'one': 3, 'two': 2, 'three': 3, 'four': 4}
>>> 

3.字典的特点

① 可存放多个值,key-value存取,取值速度快

>>> empty = {}
>>> type(empty)
<class 'dict'>
>>> dic = {'x':'hello','y':'world'}
>>> type(dic)
<class 'dict'>
>>> 

② key必须是不可变类型(数、元组、字符串),value可以是任何类型

>>> dic = {1:'hello',2:'world'}
>>> dic = {'x':'hello','y':'world'}
>>> dic = {(1,2,3):'hello','y':'world'}
>>> dic = {[1,2,3]:'hello','y':'world'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> dic = {{1,2,3}:'hello','y':'world'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> dic = {{'x':'hello'}:'hello','y':'world'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

③ 可修改指定key对应的值,可变

>>> dict1 = {'one': 1, 'two': 2, 'three': 3}
>>> dict1['one'] = 3
>>> dict1
{'one': 3, 'two': 2, 'three': 3}

③ 讲究映射,不讲顺序

>>> dict1[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 2

4.字典的内置方法

>>> dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

详细如下下:

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

① fromkeys():创建并返回一个新的字典,第一个参数是字典的键,第二个是可选参数,是传入键对应的值,不提供默认是None

>>> dict1 = {}
>>> dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
>>> dict2 = {}
>>> dict2.fromkeys((1,2,3,),'number')
{1: 'number', 2: 'number', 3: 'number'}
>>> dict3 = {}
>>> dict3.fromkeys((1,2,3),('one','two','three'))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
>>> 

② items()  values()和keys():访问字典的三种方法

keys():返回字典中的键   

>>> dict1.keys()
dict_keys([])
>>> dict1 = {}
>>> dict1 = dict1.fromkeys(range(32),'呵')
>>> dict1.keys()
dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])
>>> 

values():返回字典中的所有的值   

>>> dict1.values()
dict_values(['呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵', '呵'])

items():返回字典中的键值对,也就是项

>>> dict1.items()
dict_items([(0, '呵'), (1, '呵'), (2, '呵'), (3, '呵'), (4, '呵'), (5, '呵'), (6, '呵'), (7, '呵'), (8, '呵'), (9, '呵'), (10, '呵'), (11, '呵'), (12, '呵'), (13, '呵'), (14, '呵'), (15, '呵'), (16, '呵'), (17, '呵'), (18, '呵'), (19, '呵'), (20, '呵'), (21, '呵'), (22, '呵'), (23, '呵'), (24, '呵'), (25, '呵'), (26, '呵'), (27, '呵'), (28, '呵'), (29, '呵'), (30, '呵'), (31, '呵')])
>>> 

③ get():访问字典项,当键不存在时,get方法不会报错,而是返回一个None

>>> dict1.get(31)
'呵'
>>> dict1.get(32)
>>> 

还可以在第二个参数设置对应的默认返回值

>>> dict1.get(32,'没找到')
'没找到'
>>> 

优点:字典在检查键的成员资格比序列更高效,当数据规模相当大的时候,差距明显,原因在于字典采用哈希的方法一对一找到成员,而序列是才有迭代的方式逐个比对 ,字典查找的是键,而序列查找的是值而不是索引号

④ clear():清空字典

>>> dict1
{0: '呵', 1: '呵', 2: '呵', 3: '呵', 4: '呵', 5: '呵', 6: '呵', 7: '呵', 8: '呵', 9: '呵', 10: '呵', 11: '呵', 12: '呵', 13: '呵', 14: '呵', 15: '呵', 16: '呵', 17: '呵', 18: '呵', 19: '呵', 20: '呵', 21: '呵', 22: '呵', 23: '呵', 24: '呵', 25: '呵', 26: '呵', 27: '呵', 28: '呵', 29: '呵', 30: '呵', 31: '呵'}
>>> dict1.clear()
>>> dict1
{}
>>> 

注意:使用变量名赋值为一个空字典达到清空字典的目的是有问题的

>>> a = {'one':1,'two':2,'three':3}
>>> b = a
>>> a = {}
>>> a
{}
>>> b
{'one': 1, 'two': 2, 'three': 3}
>>> 

a,b指向同一个字典,然后试图将a指向一个空字典达到清空的目的,但是原来的字典并没有被清空,只是a换了个指向而已

这种做法容易留下安全隐患

⑤ copy():复制字典-----浅copy

>>> a = {1:'one',2:'two',3:'three'}
>>> b = a.copy()
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> id(a)
2681113548768
>>> id(b)
2681110925104
>>> a[1] = 'four'
>>> a
{1: 'four', 2: 'two', 3: 'three'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
>>> 

⑥ pop() 和 popitem()

pop():给定键弹出对应值

popitem():弹出一个项

>>> a = {1: 'one', 2: 'two', 3: 'three'}
>>> a.pop(2)
'two'
>>> a
{1: 'one', 3: 'three'}
>>> a.popitem()
(3, 'three')
>>> a
{1: 'one'}
>>> 

⑦ setdefault():与get()方法相似,setdefault()在字典中找不到相应的键时会自动默认添加None,可以设置值

>>> a = {1: 'one', 2: 'two', 3: 'three',4:'four'}
>>> a.setdefault(3)
'three'
>>> a.setdefault(5)
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: None}
>>> a.setdefault(6,'six')
'six'
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: None, 6: 'six'}
>>> 

⑧ update():更新字典

>>> b = {'one':1,'two':2,'three':3}
>>> b.update(one=3)
>>> b
{'one': 3, 'two': 2, 'three': 3}
>>> 

作业题:

1. 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。#即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

item = [11,22,33,44,55,66,77,88,99,90]
item1 = []
item2 = []
item3 = {'k1':item1,'k2':item2}
for i in item:
    if i > 66:
        item1.append(i)
    else:
	item2.append(i)
print(item3)

2.统计s='hello alex alex say hello sb sb'中每个单词的个数,结果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}

s = 'hello alex alex say hello sb sb'
list1 = s.split()
dict1 = {}
for i in list1:
    if i in dict1.keys():
        dict1[i] += 1
    else:
	dict1[i] = 1
print(dict1)
s = 'hello alex alex say hello sb sb'
list1 = s.split()
dict1 = {}
for i in list1:
    dict1[i] = list1.count(i)
print(dict1)
s = 'hello alex alex say hello sb sb'
list1 = s.split()
dict1 = {}
for i in list1:
	dict1.setdefault(i,list1.count(i))
print(dict1)

3.查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素

#li = ["alec", " aric", "Alex", "Tony", "rain"]
#tu = ("alec", " aric", "Alex", "Tony", "rain") 

#dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"

li = ["alec", " aric", "Alex", "Tony", "rain"]
tu = ("alec", " aric", "Alex", "Tony", "rain") 
dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}

for i in li:
    b = i.strip()
    if b.startswith('a') or b.startswith('A'):
	    if b.endswith('c'):
		print(b)

for i in tu:
    c = i.strip()
    if c.startswith('a') or c.startswith('A'):
	    if c.endswith('c'):
		print(c)

for i in dic:
    d = dic[i].strip()
    if d.startswith('a') or d.startswith('A'):
	    if d.endswith('c'):
		print(d)

4.用户交互,显示省市县三级联动的选择

dic = {
    "河北":{
        "石家庄" :["鹿泉","藁城","元氏"],
        "邯郸" : ["永年","涉县","磁县"]
    },
    "河南":{
        "郑州":["巩义","登封","新密"],
        "开封":["金明","鼓楼","通许"]
    },
    "山西":{
        "太原":["古交","清徐","阳曲"],
        "大同":["天镇","阳高","广灵"]
    }
}

aa = input('输入省份:')
for a in dic:
    if a == aa:
	bb = input('输入市名:')
	for b in dic[aa]:
	    if b == bb:
		cc = input('输入县名:')
		for c in dic[aa][bb]:
		    if c == cc:
			print(dic[aa][bb])

5.编写一个简单的通讯录

print('欢迎进入通讯录程序')

print('''
1.查询联系人资料
2:插入新的联系人
3:删除已有联系人
4:退出通讯录程序
''')

contacts = dict()

while True:
    choice = int(input('请输入相关的指令代码:'))
    if choice == 1:
        name = input('请输入联系人姓名:')
        if name in contacts:
            print(name,':',contacts[name])
        else:
            print('您输入的姓名不在通讯录')
    if choice == 2:
        name = input('请输入联系人的姓名')
        if name in contacts:
            print('您输入的姓名已经存在',end='')
            print(name,':',contacts[name])
            if input('是否修改用户资料(YES/NO):') == 'YES':
                contacts[name] = input('请输入用户联系电话:')
            else:
                contacts[name] = input('请输入用户联系电话:')
    if choice == 3:
        name = input('请输入联系人姓名:')
        if name in contacts:
            contacts.pop(name)
        else:
            print('您输入的联系人不存在')
    if choice == 4:
        break

print('感谢使用通讯录')

猜你喜欢

转载自blog.csdn.net/mr_humi/article/details/80850572