Python(4)--字典

Python(4)--字典

字典

是一种Mapping的数据结构(如hashmap)

def main():
    # 不使用字典的情况下模拟映射
    names = ['Tom','Alice','Eric']
    numbers = ['2341','9102','3157']
    # 找到Tom的电话
    print(numbers[names.index('Tom')])
if __name__ == '__main__':
    main()
# 创建一个字典
>>> person_info = [('name','Tom'),('age','100')]
>>> d = dict(person_info)
>>> d
{'name': 'Tom', 'age': '100'}
>>> d['name']
'Tom'

>>> d2 = dict(name='Jerry',phoneNum='12345')
>>> d2
{'name': 'Jerry', 'phoneNum': '12345'}

基本操作

# 返回字典中的k-v个数
>>> len(d2)
2
# 获取对应键的值
>>> d2['name']
'Jerry'
# 添加一个键值对
>>> d2['age'] = 22
>>> d2
{'name': 'Jerry', 'phoneNum': '12345', 'age': 22}
# 判断是否存在该键
>>> 'age' in d2
True
# 删除k-v
>>> del d2['phoneNum']
>>> d2
{'name': 'Jerry', 'age': 22}

键的类型:可以为整数,浮点,字符串,元组 任何的不可变类型
字典中没有包含键值对时也可以进行赋值,自动添加

# 快速初始化一个字典的方式
>>> d3 = {}
>>> d3[20] = 'aaa'
>>> d3
{20: 'aaa'}
def main():
    people = {
        'Alice':{
            'phone':'1234',
             'country':'America'
        },

        'Tom':{
            'phone':'4321',
            'country':'China'
        }
    }
    # output
    labels = {
        'phone':'phone number',
        'country':'country'
    }

    name = input("Name: ")

    req = input('Phone number(p) or country(c)? ')

    if req == 'p':
        key = 'phone'
    if req == 'c':
        key = 'country'

    if name in people:
        print("{}'s {} is {}".format(name,labels[key],people[name][key]))

if __name__ == '__main__':
    main()
# 字典直接应用于字符串格式
>>> "{name}'s age is {age}".format_map(person)
"aaa's age is 20"
# 使用字典+字符串格式填充Html模板
def main():
    template = '''<html>
    <head><title>{title}</title></head>
    <body>
    <h1>{title}</h1>
    <p>{text}<p>
    </body>
    </html>
    '''
    data = {'title':'Home page','text':'Welcome'}
    print(template.format_map(data))

if __name__ == '__main__':
    main()

字典方法

# 清空字典,返回None
>>> person
{'name': 'aaa', 'age': 20}
>>> res = person.clear()
>>> person
{}
>>> print(res)
None

>>> x = {}
>>> y = x
>>> x['key'] = 'value'
# 清空x并不会影响到y x.clear()则不同
>>> x = {}
>>> y
{'key': 'value'}

# copy()浅拷贝
>>> x = {'username': 'admin','machine':['foo','bar']}
>>> y = x.copy()
# 如果是修改(就地替换)原件会受影响
>>> y['machine'].remove('bar')
>>> y
{'username': 'admin', 'machine': ['foo']}
>>> x
{'username': 'admin', 'machine': ['foo']}
# 仅作替换值不会影响原件
>>> y['username'] = 'user'
>>> y
{'username': 'user', 'machine': ['foo']}
>>> x
{'username': 'admin', 'machine': ['foo']}

# 深拷贝 副本和原件互不影响
>>> from copy import deepcopy
>>> d = {}
>>> d['name'] = ['Tom','Jerry']
>>> c = d.copy()
>>> c
{'name': ['Tom', 'Jerry']}
>>> dc = deepcopy(d)
>>> d['name'].append('Alice')
>>> c
{'name': ['Tom', 'Jerry', 'Alice']}
>>> dc
{'name': ['Tom', 'Jerry']}


# 创建一个包含键值的字典,值为None
>>> {}.fromkeys(['name','age'])
{'name': None, 'age': None}
# 直接使用类型调用
>>> dict.fromkeys(['name','age'])
{'name': None, 'age': None}
# 提供特定的值
>>> dict.fromkeys(['name','age'],'Unknow')
{'name': 'Unknow', 'age': 'Unknow'}

# get()通过key获取value 如果不存在返回None
>>> d = {}
>>> print(d.get('name'))
None
>>> d['name'] = 'Tom'
>>> print(d.get('name'))
Tom
def main():
    people = {
        'Alice':{
            'phone':'1234',
             'country':'America'
        },

        'Tom':{
            'phone':'4321',
            'country':'China'
        }
    }
    # output
    labels = {
        'phone':'phone number',
        'country':'country'
    }

    name = input("Name: ")

    req = input('Phone number(p) or country(c)? ')

    if req == 'p':
        key = 'phone'
    if req == 'c':
        key = 'country'

    person = people.get(name,{})
    label = labels.get(key,key)
    # 在没有找到key时,返回
    res = person.get(key,'no available')

    print("{}'s {} is {}.".format(name,label,res))

if __name__ == '__main__':
    main()
# 返回字典得k-v序列,顺序不一定
>>> d = {'title':'google','url':'www.google.com'}
>>> d.items()
# 返回一个字典视图
dict_items([('title', 'google'), ('url', 'www.google.com')])
# 操作这个视图
>>> it = d.items()
>>> len(it)
2
>>> ('title','google') in it
True

# 删除一个键值对,返回受影响的条数
>>> d = {'x':1,'y':2}
>>> d.pop('x')
1
>>> d
{'y': 2}

# 随机弹出一个元素
>>> d = {'title':'google','url':'www.google.com'}
>>> d.popitem()
('url', 'www.google.com')
>>> d
{'title': 'google'}

# setdefault('key','val')类似于get('key') 存在键值则返回键值否则返回默认值
>>> d = {}
>>> d.setdefault('name','UNLNOW')
'UNLNOW'
>>> d
{'name': 'UNLNOW'}
>>> d['name'] = 'Tom'
>>> d.setdefault('name','UNKNOW')
'Tom'
>>> d
{'name': 'Tom'}

# 更新字典update()
>>> d = {'title':'google','url':'www.google.com'}
>>> x = {'title':'QQ','url':'www.qq.com'}
>>> d.update(x)
>>> d
{'title': 'QQ', 'url': 'www.qq.com'}

# 返回一个值的视图
>>> d
{'title': 'QQ', 'url': 'www.qq.com'}
>>> d.values()
dict_values(['QQ', 'www.qq.com'])
posted @ 2020-08-09 18:49  Dave-Mo  阅读(70)  评论(0)    收藏  举报