码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习笔记——Day3

时间:2016-08-23 23:35:50      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

Python字典(Dictionary)

字典是一种可变容器模型,可存储任意类型对象。

字典的每个键值(key => value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中,格式如下所示:

 

 d = {key1 : value1, key2 : value2 }

 

字典的特点:

键必须是唯一的,但值则不必唯一。

值可以取任何数据类型,但键必须是不可变的类型。

  不可变类型:数字、字符串、元组;

  可变类型:列表、字典。

字典中键值是无序的。

1、创建字典

方法1:

1 dic = {ID:123124,name:oliver,age:18

输出

{name: oliver, age: 18, ID: 123124}

 

方法2:

1 dic = dict(((ID,234234),))   #括号后的逗号表示第二对括号里边是一个序列

输出:

{ID: 234234}

2、访问字典

通过key去查找。

例1:

1 dic = {ID:123124,name:oliver,age:18}
2 print(dic[name])

输出:

oliver

例2:

1 dic = {ID:123124,name:oliver,age:18}
2 print(list(dic.keys()))

输出:

[age, ID, name]

例3:

1 dic = {ID:123124,name:oliver,age:18}
2 print(list(dic.values()))

输出:

18, 123124, oliver]

例4:

1 dic = {ID:123124,name:oliver,age:18}
2 print(list(dic.items()))

输出:

[(ID, 123124), (age, 18), (name, oliver)]

2、更新字典

若不存在,将dic2中的键值加入dic;若存在,则更新值
1 dic = {ID:123124,name:oliver,age:18}
2 dic2 = {1:122,123:123}
3 dic.update(dic2)
4 print(dic)

输出:

{age: 18, ID: 123124, 1: 122, name: oliver, 123: 123}

 

2、删除字典

清空字典

1 dic = {ID:123124,name:oliver,age:18}
2 print(dic.clear()) 

输出:

None

删除键值对

1 dic = {ID:123124,name:oliver,age:18}
2 del dic[name] 
3 print(dic)

输出:

{age: 18, ID: 123124}

删除键值对,并返回该key对应的值

1 dic = {ID:123124,name:oliver,age:18}
2 print(dic.pop(age))

输出:

18
{ID: 123124, name: oliver}

随机删除键值对,并以元组的形式返回删除的键值对

1 a = dic.popitem() 
2 print(a,dic)

输出:

(ID, 123124) {age: 18, name: oliver}

setdefault()

如果字典中存在此key,则不做修改;如果不存在,则添加键值。该方法还可以返回添加的值。

1 dic = {ID:123124,name:oliver,age:18}
2 ret = dic.setdefault(hobby,film)
3 print(dic)
4 print(ret)

输出:

{name: oliver, ID: 123124, hobby: film, age: 18}
film

 

fromkeys()

 

1 dic = {ID:123124,name:oliver,age:18}
2 dic2 = dict.fromkeys([host1,host2],test)
3 print(dic)
4 print(dic2)

输出:

{ID: 123124, age: 18, name: oliver}
{host2: test, host1: test}

 

sorted()

将字典中的键进行排序。

1 dic = {111:aa,554:bb,211:ds,121:asdf}
2 print(sorted(dic))

输出:

[111, 121, 211, 554]

按照键对字典进行排序。

1 dic = {111:aa,554:bb,211:ds,121:asdf}
2 print(sorted(dic.items()))

输出:

[(111, aa), (121, asdf), (211, ds), (554, bb)]

 

3、字典遍历

1 dic = {ID:123124,name:oliver,age:18}
2 for i in dic:
3     print(i,dic[i])

输出:

name oliver
age 18
ID 123124

 

Python学习笔记——Day3

标签:

原文地址:http://www.cnblogs.com/pyramid1001/p/5800797.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!