Python3学习之路~字典操作

字典的特点:无序,键唯一

字典中的键是唯一的需要使用不可变类型作为键名;
值是可以为列表,字典,整型,字符串,元组。
通过键名映射指向值。
python 不可变类型:整型,字符串,元组
可变类型:列表,字典,集合

1、字典创建
 D1={}
D2={1:'a','key':2,(2,2):'e','d':{1:'w',2:'d'}}    #冒号构造     1、使用 {  }和 : 直接创建
print(D2)# {1: 'a', 'key': 2, 'd': {1: 'w', 2: 'd'}, (2, 2): 'e'} 
D3=dict([('a',1),('b',2)])    #使用可以是一对数据组成的元组或列表,可以使用zip   2、使用dict和成对数据创建
print(D3) # {'b': 2, 'a': 1}
D4=dict(name='bob',age=23)    #使用等号构造    3、使用dict和 键=值  创建
print(D4) #{'age': 23, 'name': 'bob'}
zip函数创建
name=('tom','bob','harry')
age=(54,36,12)
D5=dict(zip(name,age))        4、使用dict和zip(两个序列)创建
print(D5)#  {'tom': 54, 'bob': 36, 'harry': 12}
dict.formkeys创建字典
a=('tom','jerry','bob')
D6=dict.fromkeys(a,'student')     5、使用dict.fromkeys(序列,默认值)创建
print(D6)# {'tom': 'student', 'jerry': 'student', 'bob': 'student'}
字典解析
D7={'%s'%x:x**2 for x in range(10) if x%2==1}
print(D7)#{'3': 9, '1': 1, '7': 49, '9': 81, '5': 25}
2、字典属性
dir(dict)
 ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
3、访问字典
D={'a':1,'b':2,'c':3}
print(D['a'])     #3 1
属性访问
print(D.keys()) 
dict_keys(['b', 'a', 'c'])  #键
D.values()
dict_values([2, 1, 3])  #值
D.items()
dict_items([('b', 2), ('a', 1), ('c', 3)]) #键+值

分别取键、值
print(D.values(), D.keys())
同时取字典的键、值,dict1.items(),这里同样加s和括号
print(dict1.items())
结果: dict_items([('d', 4), ('a', 2), ('c', 8), ('b', 3)])

4、删除字典

删除所有 
1 >>> D={'a':1,'b':2}
2 >>> D.clear()
3 >>> D
4 {}
根据键删除单个条目
1 >>> D
2 {'b': 2, 'a': 1, 'c': 3}
3 >>> del D['a']
4 >>> D
5 {'b': 2, 'c': 3}

info={'stu1101': 'Amy', 'stu1102': 'Bob', 'stu1103': 'Cindy', 'stu1104': 'David'}
info.pop("stu1101") #标准删除
del info["stu1103"] #换个姿势删除,del是Python自带的,想删谁就删谁
info.popitem() #随机删除
5、增加、修改条目
1 >>> D={'a':1,'b':2,'c':3}
2 >>> D['a']=10
3 >>> D
4 {'b': 2, 'a': 10, 'c': 3}
5 >>> D['d']=9
6 >>> D
7 {'d': 9, 'b': 2, 'a': 10, 'c': 3}

合并字典
1 >>> D={'a':1,'b':2}
2 >>> D2={'test':0}
3 >>> D.update(D2)
4 >>> D
5 {'b': 2, 'a': 1, 'test': 0}
len(dict)	计算字典元素个数,即键的总数。
str(dict)	输出字典,以可打印的字符串表示。
type(variable)	返回输入的变量类型,如果变量是字典就返回字典类型。
info = {'stu1101': "Amy",'stu1102': "Bob",'stu1103': "Cindy"}
for key in info:
print(key,info[key]) #方法1,高效,建议使用
dict_0 = {'color': 'green', 'points': 5} 
dict_1 = {'color': 'yellow', 'points': 10} 
dict_2 = {'color': 'red', 'points': 15}
lists = [dict_0, dict_1, dict_2]
for dict in lists: 
  print(dict)
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
访问字典里值 dict['Beth']
修改字典  dict['Beth'] = 9105
删除字典元素
del dict['Name']  # 删除键是'Name'的条目
dict.clear()      # 清空词典所有条目
del dict          # 删除词典
Python字典包含了以下内置函数:
1、cmp(dict1, dict2):比较两个字典元素。
2、len(dict):计算字典元素个数,即键的总数。
3、str(dict):输出字典可打印的字符串表示。
4、type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。

radiansdict.clear()    #删除字典内所有元素
radiansdict.copy()    #返回一个字典的浅复制
radiansdict.fromkeys()    #创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
radiansdict.get(key, default=None)    #返回指定键的值,如果值不在字典中返回default值
radiansdict.has_key(key)    #如果键在字典dict里返回true,否则返回false
radiansdict.items()    #以列表返回可遍历的(键, 值) 元组数组
radiansdict.keys()    #以列表返回一个字典所有的键
radiansdict.setdefault(key, default=None) #和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
radiansdict.update(dict2)    #把字典dict2的键/值对更新到dict里
radiansdict.values()    #以列表返回字典中的所有值

案例

user_0 = {
   'username': 'efermi',
   'first': 'enrico',
   'last': 'fermi',
}
for key, value in user_0.items():
   print("\nKey: " + key)
   print("Value: " + value)

favorite_languages = {
   'jen': 'python',
   'sarah': 'c',
   'edward': 'ruby',
   'phil': 'python',
}
for name, language in favorite_languages.items():
   print(name.title() + "'s favorite language is " + language.title() + ".")

for name in favorite_languages.keys():
   print(name.title())

或省略keys(),输出不变
for name in favorite_languages:
   print(name.title())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值