笔记-字典
1.字典
operator_dict={'<':'less than','==':'equal'}
print('Here is the original dict:')
for x in sorted(operator_dict): #这样会返回一个list 只包括字典的目录而没有内容
print(f'Operator {x} means {operator_dict[x]}.') # 注意format 函数的使用
print(" ")
operator_dict['>']='greater than'
print("The dict was changed to:")
for x in sorted(operator_dict):
print(f'Operator {x} means {operator_dict[x]}.')
2.result_dict.keys() 返回的是一个字典的键
3.my_dict_1 = {'name':'Niuniu','Student ID':1}
my_dict_2 = {'name':'Niumei','Student ID':2}
my_dict_3 = {'name':'Niu Ke Le','Student ID':3}
dict_list = []
dict_list.append(my_dict_1)
dict_list.append(my_dict_2)4
dict_list.append(my_dict_3)
这个最后的my_dict_3,包括三个字典的list
4.
cities_dict = {'Beijing': {'capital': 'China'},'Moscow': {'capital': 'Russia'},'Paris': {'capital': 'France'}}
cities_dict1 =sorted(cities_dict) #这里返回的是一个只包含字典的键值的列表,sorted是对键排序并返回键。
for i in cities_dict1:
print(f"{i} is the capital of {cities_dict[i]['capital']}!")
通过i去取citie_dict里面的具体的字典,再进一步取值。
5.sorted 函数的具体用法,对于字典
result_dict = {
'Allen': ['red', 'blue', 'yellow'],
'Tom': ['green', 'white', 'blue'],
'Andy': ['black', 'pink']
}
for m, n in sorted(result_dict.items()):
print("%s's favorite colors are:" % m)
for o in n:
print(o)
#print(type(sorted(result_dict.items())))
#这个会变成一个二维的列表,三个小列表,每个小列表中有一个单独的一个元素是表示键,另外一个元素是字典的value所组成的一个元素。
6.生成字典
zip()将可迭代对象封装成元素对应的元组形式,使用dict转换成字典格式。
name = input().split()
language = input().split()
print(dict(zip(name,language)))
7.查字典
dic1={'a': ['apple', 'abandon', 'ant'], 'b': ['banana', 'bee', 'become'], 'c': ['cat', 'come'], 'd': 'down'}
x=input()
for i in dic1[x]:
print(i,end=' ') #这样确保结果是在同一行,而没有换行。
8.新增字典项目
my_dict = {'a': ['apple', 'abandon', 'ant'],
'b': ['banana', 'bee', 'become'],
'c': ['cat', 'come'],
'd': 'down'}
new_key = input()
new_valu = input()
keys = my_dict.keys()#提取字典的键值
if new_key in keys:
my_dict[new_key].append(new_valu)
else:
my_dict[new_key] = new_valu
print(my_dict)
正常添加新值的方法
student = {
"name": "Alice",
"age": 20
}
# 添加新的键值对
student["gender"] = "female"
student["grade"] = "A"
print(student)
9.输入一段字符串,统计各个字母出现的频次
#方法一
# ls1 = list(input())
# ls2 = [ls1.count(i) for i in ls1]
# print(dict(zip(ls1,ls2)))
#方法二
# from collections import Counter
# ls1 = input()
# print(dict(Counter(ls1)))