6. 字典

基于网络课程《Python全栈开发专题》 记录笔记,请支持正版课程

字典

phone = {'移动':10086, '联通':10010, '电信':10000}
print(phone['移动'])   # 10086

dict()

# 在字典中,key/value 的数据类型可以不一致
items = [['移动', 10086], ('电信', 10000), ['联通', 10010], (1, '捣乱的')]
d = dict(items)    # {'移动': 10086, '电信': 10000, '联通': 10010, 1: '捣乱的'}

# 用命名参数
d1 = dict(name='二狗', sex='女', age='48')  # {'name': '二狗', 'sex': '女', 'age': '48'}

dict练习:

items = []
while True:
    key = input('Input key: ')
    if key == 'exit()':
        break
    value = input('Input value: ')
    items.append([key, value])
print(dict(items))

字典的基本操作

# len
items = {'移动':10086, '联通':10010, '电信':10000}
print(len(items))   # 3

# 修改字典里面的值:有key的修改,没有的添加
items['移动'] = 1008611
items['T-Moblie'] = 'I do not know'
print(items)   # {'移动': 1008611, '联通': 10010, '电信': 10000, 'T-Moblie': 'I not know'}

# in
print('CMCC' in items)
print('T-Moblie' in items)

字典基本操作练习:

IDEs = {
    'eclipse':
    {
     'languages': ['Java', 'Python', 'JavaScript', 'PHP'],
     'organization': 'Eclipse基金会'
    },
    'vsualstudio':
    {
     'languages': ['C#', 'C++', 'VB.NET'],
     'organization': '微软'
    },
    'webstorm':
    {
     'languages': ['JavaScript', 'Node.js', 'Java', 'Kotlin'],
     'organization': 'JetBrains'
    }
}

labels = {'languages':'支持的编程语言', 'organization':'所属机构'}

IDE = input('输入IDE的名字: ')
# 去空,小写
findIDE = IDE.strip().lower()

if not findIDE in IDEs:
    print('找不到这个IDE!')
else:
    choice = input('要查找IDE支持的语言(lang)还是所属机构(org): ')
    if choice == 'lang':
        print(labels['languages'], ':', IDEs[findIDE]['languages']);
    elif choice == 'org':
        print(labels['organization'], ':', IDEs[findIDE]['organization']);
    else:
        print('好好输入,别瞎整!')

用format_map方法格式化字符串

# 列表的
values1 = (1, 2, 'hello')
str1 = 'abc %d  xyz, %d, %s world'
print(str1 % values1)

# 字典的
values2 = {'title':'极客起源', 'url':'http://www.baidu.com', 'company':'你猜'}
str2 = """

    
        {title}
        
    
    
        

{title}

{company} """ print(str2.format_map(values2)) ''' 输出如下: 极客起源

极客起源

你猜 '''

序列与迭代

d = {'name': 'Bill', 'age':20, 'sex':"男", 'salary': 5000.25}

# 迭代字典中的key
for key in d:
    print('{} = {}'.format(key, d[key]), end="   ")

print()
# 同时迭代key-value
for key, value in d.items():
    print('{} = {}'.format(key, value), end="   ")

print()
# 并行迭代
list1 = [1, 2, 3, 4, 5]
list2 = ['a', 'b', 'c', 'd', 'e']
for i in range(len(list1)):
    print("lsit1[{index}] = {}, list2[{index}] = {}".format(list1[i], list2[i], index=i))
    
print()
# 压缩迭代
for value in zip(list1, list2):
    print(value, end=' ')
# (1, 'a') (2, 'b') (3, 'c') (4, 'd') (5, 'e')

# 压缩迭代 + dict() => 把两个列表转为一个字典
print()
items = []
for value in zip(list2, list1):
    print(value, end=' ')
    items.append(value)
print()
d1 = dict(items)
print(d1)


# 反转排序迭代
values1 = [4, 1, 5, 6, 3, 9, 7]
print(sorted(values1))   # [1, 3, 4, 5, 6, 7, 9]
values2 = reversed(values1)
for v in values2:
    print(v, end=" ")
    
print()
print(''.join(list(reversed('abcdefg'))))

clear方法

names1 = {'Bill':20, 'Mike':30, 'John':50}
names2 = names1

names1['Bill'] = 45
print(names2)   # {'Bill': 45, 'Mike': 30, 'John': 50}

# 使用这种方法,names2不会被清空
# names1 = {}
print(names2)  # {'Bill': 45, 'Mike': 30, 'John': 50}

# 使用clear()方法,names1 和 names2 都会被清空
names1.clear() 
print(names1)  # {}
print(names2)  # {}

复制字典: copy 和 deepcopy

p1 = {'name':'Mike', 'age':30, 'fullName':['Bill', 'Gates']}

# copy 浅层复制
p2 = p1.copy()
print(p2)

p1['age'] = 60
# 复制了第一层 !
print(p1)   # 60
print(p2)   # 30

# 如果是:p1['fullName'] = ['Bill', 'Clinton'], p2不会变的,“复制第一层”!
p1['fullName'][1] = 'Clinton'
print(p1)   # ['Bill', 'Clinton']
print(p2)   # ['Bill', 'Clinton']


# deepcopy
from copy import deepcopy
p3 = deepcopy(p1)
p1['fullName'][1] = 'xxx'
print(p1)   # xxx
print(p2)   # xxx
print(p3)   # Clinton

根据key创建字典: fromkeys

d1 = {}.fromkeys(['name', 'company', 'salary']);
print(d1)  # {'name': None, 'company': None, 'salary': None}

d2 = {}.fromkeys(('name', 'company', 'salary'));
print(d2)  # {'name': None, 'company': None, 'salary': None}

# 非空字典,没用
d3 = {'age':18}.fromkeys(('name', 'company', 'salary'));
print(d3)  # {'name': None, 'company': None, 'salary': None}

# 指定默认值
d4 = {}.fromkeys(('name', 'company', 'salary'), 'default')
print(d4)  # {'name': 'default', 'company': 'default', 'salary': 'default'}

get方法

dict = {'name':'Bill', 'age':30}
print(dict['age'])
# print(dict['salary'])  # key不存在会抛出异常

print(dict.get('age'))  # 30
print(dict.get('salary')) # None, 用get方法,不会抛出异常

一个小练习:

d = {'China':'伟大祖国', 'Apple':'苹果', 'pen':'盆,啊不是,钢笔', 'Android':'安卓'}

while True:
    word = input('请输入英文单词:')
    
    if word == 'exit()':
        break
    
    if d.get(word) == None:
        print('未收录的单词: {}'.format(word))
    else:
        print('"{}"的意思是:"{}"'.format(word, d.get(word)))

获取字典中的key和value(items和key方法)

# 注意,最后一个元素,我手误,写了一个None!!!
d = { 'help':'帮助', 'bike':'自行车', 'plane':'灰机', 'apple':'苹果', }

print(d.items())  
# 输出:外层是列表内层是元组
# dict_items([('help', '帮助'), ('bike', '自行车'), ('plane', '灰机'), ('apple', '苹果')])

# 遍历1
for key_value in d.items():
    print('key={key}, value={value}'.format(key=key_value[0], value=key_value[1]))

# 遍历2
for key, value in d.items():
    print('key={}, value={}'.format(key, value))

# 歪个楼
l1 = [(1, 2, 3), (4, 5, 6), ('a', 'b', 'c')]
for v1, v2, v3 in l1:
    print('v1={}, v2={}, v3={}'.format(v1, v2, v3))
    
d_items = d.items()
d['bike'] = '我把Bike修改了'
print(d_items)
# 输出如下:修改字典,items也会改变
# dict_items([('help', '帮助'), ('bike', '我把Bike修改了'), ('plane', '灰机'), ('apple', '苹果')])

# keys方法
print(d.keys())  # dict_keys(['help', 'bike', 'plane', 'apple'])

弹出字典中的值(pop和popitem)

# pop,获取指定key值,并弹出key-value对
# popitem,获取字典中最后一个key-value对

d = {'name':'Bill', 'age':18, 'salary':'3800'}
d['sex'] = '中'
d['address'] = 'ApplePark'

# pop
print(d.pop('name'))  # Bill
print(d)  # {'age': 18, 'salary': '3800', 'sex': '中', 'address': 'ApplePark'}

# popitem
for i in range(len(d)):
    x = d.popitem()
    print('key={}, value={}'.format(x[0], x[1]))
'''
key=address, value=ApplePark
key=sex, value=中
key=salary, value=3800
key=age, value=18
'''

添加但不修改value(setdefault方法)

d = {'name':'Bill', 'age':30}

# 不存在就添加,存在就修改
d['salary'] = 38000
d['age'] = 50

# 只添加不修改
print(d.setdefault('address', '中国'))  # 中国
print(d)  # {'name': 'Bill', 'age': 50, 'salary': 38000, 'address': '中国'}

print(d.setdefault('age', 99))  # 50 !!!!!
print(d)  # {'name': 'Bill', 'age': 50, 'salary': 38000, 'address': '中国'}

print(d.setdefault("abc"))   # None
print(d.setdefault("age"))   # 50

成批导入字典数据(updates方法)

d1 = {'name':'Bill', 'age':18}
d2 = {'age':55, 'address':'Xi\'an'}

# 用一个字典更新另一个字典,有的更新,没有的增加
d1.update(d2)
print(d1)   # {'name': 'Bill', 'age': 55, 'address': "Xi'an"}

获取字典中的值列表(values方法)

d = {'a':1, 'b':2, 'c': 2, 'd':3, 'e':4, 'e':911}

# 字典中key也是没有重复的,相当于java Map的put,会覆盖
print(d)   # {'a': 1, 'b': 2, 'c': 2, 'd': 3, 'e': 911}
print(d.keys())  # dict_keys(['a', 'b', 'c', 'd', 'e'])
print(d.values())  # dict_values([1, 2, 2, 3, 911])

#遍历
for val in d.values():
    print(val)

练习1:setdefault() + 随机数

d = {}
import random
for i in range(1000):
    
    key = random.randint(0, 99)
    
    # 方法1
#     if d.get(key) == None:
#         d[key] = '随便吧{}'.format(i)
    # 方法2
    d.setdefault(key, '随便吧{}'.format(i));
        
for key, value in d.items():
    print('key={}, value={}'.format(key, value))
    
print('最终的长度是:{}'.format(len(d)))

练习2:format_mat()的灵活运用

ASCII码表

  • ord(c) 获得ASCII码
  • 数字 "0 ~ 9"的ASCII码是"48 ~ 57"
  • if ord(c) in range(48, 58)判断字符是否为数字
s = 'abccc786fff987i56GG11'

number = ''
s1 = ''
index = 0
d = {}

for i in range(len(s)):
    c = s[i]
    # ord 获取ASCII码
    # range(48, 58)  0~9的ASCII码是48~57
    if ord(c) in range(48, 58):
        number += c
    else:
        if len(number) > 0:
            s1 += "{{number{}:010}}".format(index)
            d['number' + str(index)] = int(number)
            number = ''
            index += 1
        s1 += c
else:
    if len(number) > 0:
        s1 += "{{number{}:010}}".format(index)
        d['number' + str(index)] = int(number)

print('原字符串: ', s)
print('格式化字符串: ', s1)
print('格式化字典: ', d)
print('最终结果: ', s1.format_map(d))

你可能感兴趣的:(6. 字典)