yandyand

导航

python之字典操作及字典的OrderedDict 排序

#:定义字典
# stuff = {'name':'Zed','age':39,'heigh':6*12+2}
# print(stuff)

#:修改字典中的values
# stuff = {'name':'Zed','age':39,'heigh':6*12+2}
# stuff['name'] = '杨洋'
# print(stuff)

#:添加
# stuff = {'name':'Zed','age':39,'heigh':6*12+2}
# stuff[1] = "add"
# print(stuff)

#:删除
# stuff = {'name':'Zed','age':39,'heigh':6*12+2}
# del stuff['name']
# print(stuff)




# create a mapping of state to abbreviation
#创建状态到缩写的映射

# states = {
# 'Oregon':'OR',
# 'Florida':'FL',
# 'California':'CA',
# 'New York': 'NY',
# 'Michigan':'MI'
# }
#
# #create a basic set of states and some cities in them
# #创建一组基本的州和其中的一些城市
#
# cities = {
# 'CA':'San Francisco',
# 'MI':'Detroit',
# 'FL':'Jacksonville'
# }
#
# #:add some more cities
# #再增加一些城市
# cities['NY'] = 'New York'
# #:添加城市{'NY':New York}
# cities['OR'] = 'portland'
# #:添加城市{'OR':'portland'}
#
# #print out some cities
# #:打印出一些城市
# print('-'*10)
# print("NY State has: ", cities['NY'])
# #:首先打印出字典cities中的['NY'] {'NY':'New York'}
# print("OR State has: ", cities['OR'])
# #:在打印{'OR':'portland'}
#
# #print some states
# #:打印一些状态
# print('-' * 10)
# print("Michigan's abbreviation is:", states['Michigan'])
# #:打印['MI']
# print("Florida has: ", cities[states['Florida']])
# #:打印cities[states['Florida']] // 先打印states['Florida'] 得到'FL' 最后cities['FL'] 得到'Jacksonville'
#
# # do it by using the states the cities dict
# # 用州和城市的命令来做
# print('-' * 10)
# print("Michigan has: ",cities[states['Michigan']])
# #:同上先执行states['Michigan']得到'MI' 最后在cities['MI'] 得到'Detroit'
# print("florida has:",cities[states['Florida']])
# #:先执行''states['Florida'] 得到'FL' 最后在执行cities['FL'] 得到 Jacksonville
#
# # print every state abbreviation
# # 打印每个州的缩写
# print('-' * 10)
# # print(list(states.items()))
# for state,abbrev in list(states.items()):
# #:for 循环两个参数state abbrev 遍历
# # :list(states.items()) items()将字典遍历成元组 这里先将states(字典)转换成元组(items()) 在使用list()转换成列表
# print(f"{state} is abbreviated {abbrev}")
# #:遍历的时候 state变量接入 元组中的第一个值'Oregon' abbrev变量接入第二个值'OR'
# #:此时的states是列表 里面装着元组 每个元组里面 装着两个参数 所以才需要state abbrev两个变量来接入
#
#
# # print every city in state
# # 打印州内每个城市
# print('-' * 10)
# for abbrev,city in list(cities.items()):
# #:原理跟上面的for循环一样
# print(f"{abbrev} has the city {city}")
# #:分别打印两个变量
#
# #now do both at the same time
# # 现在两者同时做
# print('-' * 10)
# #:首先打印 ----------
# for state,abbrev in list(states.items()):
# #:使用for循环创建两个变量 再把字典states中的值先转换成元组 在使用list/列表 将states变量/字典/元组转换这列表
# print(f"{state} state is abbreviated {abbrev}")
# #:先打印state 也就是元组中的第一个值 在打印abbrev 这个变量
# print(f"and has city {cities[abbrev]}")
# #:在打印出cities变量中的abbrev的值 // cities[abbrev]
#
# print('-' * 10)
# # safely get a abbreviation by state that might not be there
# #:按可能不存在的州安全地获取缩写
# state = states.get('Texas')
#
# if not state: #:判断如果state 不存在
# print("Sorry, no Texas.") #:打印
# #get a city with a default value
# # 获取具有默认值的城市
# city = cities.get('Tx','Does Not Exist')
# #使用get函数查找'TX' 如果不存在'Tx' 则返回 'Does Not Exist'
# print(f"The city for the state 'Tx' is:{city}")
# #:打印The city for the state 'Tx' is 因为city 中使用get函数 不存在Tx 所以返回Does Not Exist

# '''
# 城市:
# '''
#
# city = {
# '北京':'bj',
# '上海':'sh',
# '武汉':'wh',
# '吉林':'jl',
# '河北':'hb'
# }
#
# Full_name = {
# 'bj':'北京市',
# 'sh':'上海市',
# 'wh':'武汉市',
# 'jl':'吉林省',
# 'hb':'河北省'
# }
#
#
# #:先打印出城市的缩写
# print(f"北京市的缩写是:{city['北京']}")
#
# #:打印出缩写的全称
# print(f"'hb'的全称是:{Full_name[city['河北']]}")
#
# #:追加一个城市'河南'
# city['河南'] = 'hn'
# Full_name['hn'] = '河南省'
# print(f"河南省的缩写是:{city['河南']}")
# print(f"hn的全称是:{Full_name['hn']}")
#
# #:在使用for循环将city中所有的值全部遍历出来
# for key_1,values_1 in list(city.items()):
# print(f"{key_1}的简称是{values_1}")
# print(f"{values_1}的全称是{Full_name[values_1]}")


####################字典的基本操作#################

# dict1 = {
# 'day':'Monday',
# 'name':'杨洋',
# 'city':'北京'
# }


#:基本查询
# print(dict1)

#:通过key来进行查询
# print(dict1['name'])

#:查询所有的valuse
# print(dict1.values())

#:查询所有的key
# print(dict1.keys())

#:get函数 如果查询的key值存在则返回values 如果key的值不存在则返回一个警告信息
#:先查找存在key值
# print(dict1.get('city'))
#:在查找一个不存在的值
# print(dict1.get('home','哦 home 这个值不存在'))


#:修改values
# dict1['name'] = ['yy']
# print(dict1['name'])

#:添加一个新的kye/values
# dict1['home'] = '昌平'
# print(dict1)

#:删除
#:方法1
# del dict1['name']
# print(dict1)
#######################
#:方法2
# dict1.pop('name')
# print(dict1)

#:随即删除
# dict1.popitem()
# print(dict1)


# '''
# 字典的多级嵌套
#
# '''
# av_catalog = {
# "欧美":{
# "www.youporn.com":["很多免费的,世界最大的","质量一般"],
# "www.pornhub.com":["很多免费的,也很大","比youporn高点"],
# "letmedothistoyou.com":["多是自拍,高质量图片很多","资源丰富"]
# },
# "日韩":{
# "tokyo-hot":["质量不清楚,个人已经不喜欢日韩了","听说是收费的"],
# },
# "大陆":{
# "1024":["全部免费.真好好人一生平安","服务器在国外,慢"]
# }
# }
#
# av_catalog["大陆"]["1024"][1] = "可以在国内做镜像"
# print(av_catalog)


#####################字典的其他操作##########################

# info = {
# 'stu1001':"TengLan Wu",
# 'stu1002':"Longze Loula",
# 'stu1103':"XiaoZe Maliya",
# }
#
# b = {
# 'stu1001':"liang",
# 1:2,
# 2:5
# }

#:合并字典 update
# info.update(b)
# print(info)

#:字典转化为列表 items()
# print(info.items())

#:初始化一个新的字典 fromkeys
# c = dict.fromkeys([7,8,9],"test")
# print(c)


####################字典循环#####################

# info = {
# 'stu1001':"TengLan Wu",
# 'stu1002':"Longze Loula",
# 'stu1103':"XiaoZe Maliya",
# }
#
# b = {
# 'stu1001':"liang",
# 1:2,
# 2:5
# }

#:字典的最基本的循环
# for i in info:
# print(i,info[i])
#:循环时 i = stu1001 info[i] == info[stu1001]


#:遍历字典 将字典先转换成列表在赋值给两个变量"k" "v"
# for k,v in info.items():
# :先将字典转换成列表 "[stu1001,TengLan Wu]"
# print(k,v) #: k = stu1001 v == TengLan Wu


#:字典中的数据结构

#:调用字典函数
# from collections import OrderedDict

#:设置字典
# d = OrderedDict()
# d['a'] = 1
# d['b'] = 10
# d['c'] = 8
#
# #:遍历字典'd'
# for letter in d:
# print(letter)

#:如果初始化的时候传入多个参数 那么他么的顺序是随机的 不会按照位置顺序存储
# d = OrderedDict(a=1,b=2,c=3)
# print(d)

# print('Regular dictionary:')
# d = {}
# d['a'] = 'A'
# d['b'] = 'B'
# d['c'] = 'C'
# for k,v in d.items():
# print(k,v)
# print("\nOrderDict:")
# d = OrderedDict()
# d['a'] = 'A'
# d['b'] = 'B'
# d['c'] = 'C'
# for k,v in d.items():
# print(k,v)

##############################OrderedDict##################################

# import collections
# print("Regular dictionary")
# d = {}
# d['a'] = 'A'
# d['b'] = 'B'
# d['c'] = 'C'
# for k,v in d.items():
# print(k,v) #;本来式验证无序的字典的但不知道为什么变成了有序
#
# #:调用collections 使其字典变成有序的字典
# d1 = collections.OrderedDict() #:调用OrderdDict 模块
# d1['a'] = 'A'
# d1['b'] = 'B'
# d1['c'] = 'C'
# d1['1'] = '1'
# d1['2'] = '2'
# for k,v in d1.items():
# print(k,v)


#:在来一个例子用于更好的证明
#:先看不使用OrderdDict 模块
# d2 = {}
# d2['a'] = 'A'
# d2['b'] = 'B'
# d2['c'] = 'C'
#
# d3 = {}
# d3['c'] = 'C'
# d3['a'] = 'A'
# d3['b'] = 'B'
#
# print(d2 == d3) #:判断此时的d2等于d3 虽然他们的排列顺序不一样 但是他们在内部还是处于相等的顺序
#
#
# #:在看使用OrderdDict
# import collections
# d4 = collections.OrderedDict()
# d4['a'] = 'A'
# d4['b'] = 'B'
# d4['c'] = 'C'
#
# d5 = collections.OrderedDict()
# d5['c'] = 'C'
# d5['a'] = 'A'
# d5['b'] = 'B'
#
# print(d4 == d5) #:在调用了OrderdDict 模块后 它会按照你录入字典的顺序进行排序 所以在进行比对的时候:
# '''
# d4 = {
# a : A
# b : B
# c : C
# }
#
# d5 = {
# c : C
# a : A
# b : B
# }
# '''
#:所以它们之间的不相等 返回 Flase

posted on 2020-06-08 00:17  yandyand  阅读(560)  评论(0编辑  收藏  举报