字典

字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。

python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以

字典是无序存储的,且key必须是可哈希的。可哈希表示key必须是不可变类型,

如:数字、字符串、元组。

字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型。

列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:

————>字典当中的元素是通过键来存取的,而不是通过偏移存取。

#Hostname:陈先生

#_Author:"Jayce Chan"

#Date:2019/1/9

#创建字典

#法一

dic1 = {'name':'Jayce',"age":'23',"sex":"male",'hobby':{'name':"Angle",'age':'22'}}

print(dic1)

#字典是可变类型,也可作为值来存储,但不能作键

#法二

# def __init__(self, seq=None, **kwargs): # known special case of dict.__init__

# """

# dict() -> new empty dictionary

# dict(mapping) -> new dictionary initialized from a mapping object's

# (key, value) pairs

# dict(iterable) -> new dictionary initialized as if via:

# d = {}

# for k, v in iterable:

# d[k] = v

# dict(**kwargs) -> new dictionary initialized with the name=value pairs

# in the keyword argument list. For example: dict(one=1, two=2)

# # (copied from class doc)

# """

dic2 = dict( [ ("name","Jayce"), ] )

print(dic2)

#字典两大特点:无序,键唯一

#增

dic2["Age"] = '18'

print(dic2) #{'name': 'Jayce', 'Age': '18'}

# setdefault(self, *args, **kwargs): # real signature unknown

# """

# Insert key with a value of default if key is not in the dictionary.

#

# Return the value for key if key is in the dictionary, else default.

# """

#setdefault():键不存在,在字典中中增加新的键值对,并返回相应的值

ret1 = dic2.setdefault('hobby','girl')

print(ret1)

print(dic2)

#setdefault():键存在,不改动,返回字典中相应的键对应的值

ret2 = dic2.setdefault('Age','20')

print(ret2)

print(dic2)

#查 通过键去查找

dic3 = {'name': 'Jayce', 'Age': '18', 'hobby': 'girl'}

print(dic3['hobby'])

#查键

# keys(self): # real signature unknown; restored from __doc__

# """ D.keys() -> a set-like object providing a view on D's keys """

print(dic3.keys()) #dict_keys(['name', 'Age', 'hobby'])

print(type(dic3.keys()))

#转换成列表

print(list(dic3.keys())) #['name', 'Age', 'hobby']

#查值

# values(self): # real signature unknown; restored from __doc__

# """ D.values() -> an object providing a view on D's values """

print(list(dic3.values())) # ['Jayce', '18', 'girl']

# items(self): # real signature unknown; restored from __doc__

# """ D.items() -> a set-like object providing a view on D's items """

print(list(dic3.items()))

#改

print(dic3)

dic3["Age"] = '20' #可修改

print(dic3) #{'name': 'Jayce', 'Age': '20'}

# update(self, E=None, **F): # known special case of dict.update

# """

# D.update([E, ]**F) -> None. Update D from dict/iterable E and F.

# If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]

# If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v

# In either case, this is followed by: for k in F: D[k] = F[k]

# """

dic4 = {"1":"123",'name':"冷垚"}

dic3.update(dic4)

print(dic3)

print(dic4)

#删

dic5 = {'name':"冷垚",'age':'23',"sex":'male','class':'网络1501','stuNumber':'1518064003'}

print(dic5)

#删除字典中指定键值对

del dic5['name']

print(dic5)

#删除字典中指定键值对,并返回该键值对的值

ret3 = dic5.pop("age")

print(ret3)

print(dic5)

#opitem(): 随机删除一个键值对 ,并以元组方式返回值

# popitem(self): # real signature unknown; restored from __doc__

# """

# D.popitem() -> (k, v), remove and return some (key, value) pair as a

# 2-tuple; but raise KeyError if D is empty.

# """

a = dic5.popitem()

print(a)

print(dic5)

# clear() 清空字典

# clear(self): # real signature unknown; restored from __doc__

# """ D.clear() -> None. Remove all items from D. """

dic5.clear()

print(dic5)

#删除整个字典

# del dic5

# print(dic5)

#####其他操作以及涉及到的方法#####

#dict.fromkeys() :创建字典

# fromkeys(*args, **kwargs): # real signature unknown

# """ Create a new dictionary with keys from iterable and values set to value. """

dic6 = dict.fromkeys(['A','B','C'],'ad')

print(dic6) #{'A': 'ad', 'B': 'ad', 'C': 'ad'}

dic6['B'] = "123"

print(dic6) #{'A': 'ad', 'B': '123', 'C': 'ad'}

dic7 = dict.fromkeys(['A','B','C'],['aa','bb'])

print(dic7) #{'A': ['aa', 'bb'], 'B': ['aa', 'bb'], 'C': ['aa', 'bb']}

dic7['B'][1]='cc'

print(dic7) #{'A': ['aa', 'cc'], 'B': ['aa', 'cc'], 'C': ['aa', 'cc']}

# 字典的嵌套

av_catalog = {

"欧美":{

"www.youporn.com": ["很多免费的,世界最大的","质量一般"],

"www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],

"letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],

"x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]

},

"日韩":{

"tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]

},

"大陆":{

"1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]

}

}

av_catalog["大陆"]["1024"][1] += ",可以用爬虫爬下来"

print(av_catalog["大陆"]["1024"])

#排序

# sorted(*args, **kwargs): # real signature unknown

# """

# Return a new list containing all items from the iterable in ascending order.

#

# A custom key function can be supplied to customize the sort order, and the

# reverse flag can be set to request the result in descending order.

# """

dic8 = {5:'555',2:'666',4:"444"}

print(sorted(dic8.values()))

print(sorted(dic8.items()))

#遍历

dic00 = {'name':"冷垚",'age':'23',"sex":'male','class':'网络1501','stuNumber':'1518064003'}

#推荐使用①

#①

for i in dic00:

print(i,dic00[i])

#②

for i in dic00.items():

print(i)

#③

for i,v in dic00.items():

print(i,v)

转载于:https://www.cnblogs.com/lengyao888/p/10245452.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值