python学习笔记------字典

字典的创建
# 定义空集合, 必须set(),
# {}默认的类型为字典;
d = {}
print(type(d))

# 字典: key-value值, 键值对;
# value值可以是任意数据类型: int, float, complex, list, tuple, set, dict
d = {
    '小明': [18, '男', "请假"],
    '小虎': [18, '男', '俯卧撑']
}

print(d['小虎'])

d2 = {
    'a': 1,
    'b': 2
}

print(d2)

d3 = {
    'a': {1, 2, 3},
    'b': {2, 3, 4}
}
print(d3)

# 字典的嵌套;
students = {
    '13021001': {
        'name':'小龙',
        'age':18,
        'score':100
    },
    '13021003': {
        'name': '小凤',
        'age': 18,
        'score': 90
    }
}
print(students['13021003']['name'])

# 工厂函数;
l = list([1,2,3])
print(l)

d5 = dict(a=1, b=2)
print(d5)

cardinfo = {
    '001':'000000',
    '002':'000000'
}

# fromkeys第一个参数可以列表/tuple/str/set, 将列表的每一个元素作为字典的key值,
# 并且所有key的value值一致, 都为'000000';
print({}.fromkeys({'1', '2'}, '000000'))

# 字典必须是不可变数据类型;d = {[1,2,3]:1}(x)

# 可变数据类型:list, set,  dict
# 不可变: 数值类型, str, tuple

结果如下:

<class 'dict'>
[18, '男', '俯卧撑']
{'a': 1, 'b': 2}
{'a': {1, 2, 3}, 'b': {2, 3, 4}}
小凤
[1, 2, 3]
{'a': 1, 'b': 2}
{'2': '000000', '1': '000000'}
字典的特性
d = {
    '1': 'a',
    '8': 'b'
}

# print(d['1'])

# 字典是不支持索引的;
# print(d[0])

# 字典是不支持切片的;
# print(d[::])

# 字典的重复和连接无意义, 字典的key值是唯一的;
# print(d*3)

# 成员操作符;判断的是某个值是否为字典的key;
print('1' in d)
print('1' not in d)

# 字典for循环时, 默认遍历字典的key值;
for key in d:
    print(key)

# 遍历字典:
for key in d:
    print(key, d[key])

结果如下:

True
False
1
8
1 a
8 b
字典的增加
services = {
    "http":80,
    'ftp': 21,
    'ssh':22
}

# # 1. 增加一个元素;
#   1). 如果key值存在, 则更新对应的value值;
#   2). 如果key值不存在, 则添加对应的key-value值
services['mysql'] = 3306
print(services)

services['http'] = 550
print(services)

# 2. 添加多个key-value值;
#   1). 如果key值存在, 则更新对应的value值;
#   2). 如果key值不存在, 则添加对应的key-value值
service_backup = {
    'https':443,
    'tomcat':8080,
    'http':8080
}
services.update(service_backup)

print(services)

services.update(flask=9000, http=8080)
print(services)

# 3.setdefault添加key值;
#   1). 如果key值存在, 则不做修改;
#   2). 如果key值不存在, 则添加对应的key-value值
services.setdefault('http',9090)
print(services)

services.setdefault('oracle',44575)
print(services)

结果如下:

{'http': 80, 'ftp': 21, 'ssh': 22, 'mysql': 3306}
{'http': 550, 'ftp': 21, 'ssh': 22, 'mysql': 3306}
{'http': 8080, 'ftp': 21, 'ssh': 22, 'mysql': 3306, 'https': 443, 'tomcat': 8080}
{'http': 8080, 'ftp': 21, 'ssh': 22, 'mysql': 3306, 'https': 443, 'tomcat': 8080, 'flask': 9000}
{'http': 8080, 'ftp': 21, 'ssh': 22, 'mysql': 3306, 'https': 443, 'tomcat': 8080, 'flask': 9000}
{'http': 8080, 'ftp': 21, 'ssh': 22, 'mysql': 3306, 'https': 443, 'tomcat': 8080, 'flask': 9000, 'oracle': 44575}
字典的删除
services = {
    "http":80,
    'ftp': 21,
    'ssh':22,
    'mysql':3306
}
# 1.
# del services['http']
# print(services)

# 2. pop删除指定key的key-value对,
#   1). 如果key存在, 删除, 并且返回删除key对应的value值;
#   2). 如果key不存在, 直接报错
item = services.pop('http')
print(item)
print(services)

# item = services.pop('https')
# print(item)
# print(services)

#3. popitem删除最后一个key-value值;
item = services.popitem()
print("删除的key-value对是:", item)
print(services)

# 4. 清空字典内容;
services.clear()
print(services)

结果如下:

80
{'ftp': 21, 'ssh': 22, 'mysql': 3306}
删除的key-value对是: ('mysql', 3306)
{'ftp': 21, 'ssh': 22}
{}
字典的查看
services = {
    "http":80,
    'ftp': 21,
    'ssh':22,
    'mysql':3306
}

# 查看字典的key值;
print(services.keys())

# 查看字典的value值;
print(services.values())

# 查看字典的(key,value)值;
print(services.items())

# 1. 查看key的value值;key不存在,则报错;
print(services['http'])
# print(services['https'])

# 2. 查看key的value值;
#       key不存在, 默认返回None;
#       key不存在, 有default值, 则返回default值;

print(services.get('http'))
print(services.get('https'))
print(services.get('https', 443))

结果如下:

dict_keys(['http', 'ftp', 'ssh', 'mysql'])
dict_values([80, 21, 22, 3306])
dict_items([('http', 80), ('ftp', 21), ('ssh', 22), ('mysql', 3306)])
80
80
None
443
字典练习
# 重复的单词: 此处认为单词之间以空格为分隔符, 并且不包含,和.;
    # 1. 用户输入一句英文句子;
    # 2. 打印出每个单词及其重复的次数;

s = input("s:") # "hello java hello python"

# 把每个单词分割处理;
s_li = s.split()
print(s_li)

# 依次循环遍历列表, 
#     如果列表元素不在字典的key中,将元素作为key, 1作为value加入字典;
#     如果列表元素在字典的key中,直接更新value值, 即在原有基础上加1
words_dict = {}

for item in s_li:
    if item not in words_dict:
        words_dict[item] = 1
    else:
        # words_dict[item]  = words_dict[item] + 1
        words_dict[item]  +=  1

# 打印生成的字典;
print(words_dict)

结果:

s:hello c hello world
['hello', 'c', 'hello', 'world']
{'hello': 2, 'c': 1, 'world': 1}

# 数字重复统计:
#     1). 随机生成1000个整数;
#     2). 数字的范围[20, 100],
#     3). 升序输出所有不同的数字及其每个数字重复的次数;

import random

# 随机生成1000个整数;
all_nums = []
for item in range(1000):
# 数字的范围[20, 100],
    all_nums.append(random.randint(20,100))

# 升序输出所有不同的数字及其每个数字重复的次数;
# 对生成的1000个数字进行排序, 然后在加入到字典中,计算个数;
sorted_nums = sorted(all_nums)
nums_dict = {}
for num  in sorted_nums:
    if num in nums_dict:
        nums_dict[num] += 1
    else:
        nums_dict[num] = 1

print(nums_dict)

# sort_num_dict = {}
# 
# for num in sorted(nums_dict.keys()):
#     sort_num_dict[num]=  nums_dict[num]
# 
# print(sort_num_dict)

结果:

{20: 10, 21: 9, 22: 13, 23: 10, 24: 14, 25: 10, 26: 11, 27: 10, 28: 13, 29: 18, 30: 13, 31: 12, 32: 6, 33: 13, 34: 16, 35: 12, 36: 19, 37: 8, 38: 10, 39: 20, 40: 8, 41: 12, 42: 10, 43: 11, 44: 13, 45: 10, 46: 16, 47: 13, 48: 11, 49: 15, 50: 9, 51: 9, 52: 9, 53: 14, 54: 10, 55: 13, 56: 14, 57: 9, 58: 15, 59: 17, 60: 11, 61: 8, 62: 8, 63: 9, 64: 15, 65: 16, 66: 16, 67: 13, 68: 7, 69: 18, 70: 15, 71: 15, 72: 12, 73: 9, 74: 13, 75: 12, 76: 10, 77: 11, 78: 12, 79: 22, 80: 15, 81: 5, 82: 8, 83: 9, 84: 10, 85: 13, 86: 16, 87: 15, 88: 8, 89: 14, 90: 12, 91: 14, 92: 13, 93: 17, 94: 9, 95: 12, 96: 10, 97: 13, 98: 20, 99: 15, 100: 15}

# 1. 随机生成100个卡号;卡号以6102009开头, 后面3位依次是 (001, 002, 003, 100),
# 2. 生成关于银行卡号的字典, 默认每个卡号的初始密码为"redhat";
# 3. 输出卡号和密码信息, 格式如下:
# 卡号                     密码
# 6102009001              000000

# 存储所有卡号的列表, 也可以通过集合来存储;
card_ids = []

# 生成100个卡号的过程;
for i in range(100):
    # %.3d代表这个整形数占3位。 eg: 1--> 001;
    s = "6102009%.3d" %(i+1)
    # 将每次生成的卡号加入列表中;
    card_ids.append(s)

card_ids_dict = {}.fromkeys(card_ids, 'redhat')
# print(card_ids_dict)

print("卡号\t\t\t\t\t密码")
for key in card_ids_dict:
    print("%s\t\t\t%s" %(key, card_ids_dict[key]))


猜你喜欢

转载自blog.csdn.net/qq_41891803/article/details/81416520