您的位置:首页 > 编程语言 > Python开发

Python 字典(Dictionary)笔记

2018-01-07 15:52 211 查看
tuple1 = ("green","red","blue")
tuple2 = tuple([7,1,2,23,4,5])
print (len(tuple2)) # 6
print (max(tuple2)) # 23
print (min(tuple2)) # 1
print (sum(tuple2)) # 42
print (tuple2[0]) # 7
tuple3 = 2 * tuple1
print (tuple3) # ('green', 'red', 'blue', 'green', 'red', 'blue')
print (tuple2[2:4]) # (2, 23)
print (tuple1[-1]) # blue
for v in tuple1:
print (v,end=' ') # green red blue
print ()
print (tuple1==tuple2) # False
s1 = {1,2,4}
s1.add(6)
print (s1)        # {1,2,4,6}
print (len(s1))   # 4
print (max(s1))   # 6
print (min(s1))   # 1
print (sum(s1))   # 13
print (3 in s1)   # False
s1.remove(4)
print (s1)        # {1,2,6}

s1 = {1,2,4}
s2 = {1,4,5,2,6}
print (s1.issubset(s2))    # True
print (s2.issuperset(s1))  # True
print (s1==s2)             # False
print (s1<=s2)             # True

print (s1.union(s2))       # {1,2,4,5,6}
print (s1|s2)              # {1,2,4,5,6}

print (s1.intersection(s2))# {1,2,4}
print (s1&s2)              # {1,2,4}

print (s1.difference(s2))  # set()
print (s1-s2)              # set()

print (s1.symmetric_difference(s2))  # {5,6}
print (s1^s2)                        # {5,6}

students = {"111-58-5858":"John", "132-59-5959":"Peter"}

# add
students["234-56-9010"] = "Susan"
# modify
students["111-58-5858"] = "Smith"
# 检索
print (students["111-58-5858"])    # Smith
# 删除
del students["234-56-9010"]
# 循环
for key in students:
print (key + ":" + students[key])    # 111-58-5858:Smith  132-59-5959:Peter
# len
print (len(students))  # 2
# in, not in
print ("111-58-5858" in students)  # True
print ("111" not in students)      # True
# ==, !=
d1 = {"red":22, "blue":2}
d2 = {"blue":2, "red":22}
print (d1==d2)   # True
print (d1!=d2)   # False

#keys()
print (tuple(students.keys()))   # ('111-58-5858', '132-59-5959')
print (tuple(students.values())) # ('Smith', 'Peter')
print (tuple(students.items()))  # (('111-58-5858', 'Smith'), ('132-59-5959', 'Peter'))
print (students.get("111-58-5858"))  # Smith
print (students.pop("111-58-5858"))  # Smith
print (students.popitem())           # ('132-59-5959', 'Peter')

>>> dict = { 1 : 2, 'a' : 'b', 'hello' : 'world' }
>>> dict.values()
['b', 2, 'world']
>>> dict.keys()
['a', 1, 'hello']
>>> dict.items()
[('a', 'b'), (1, 2), ('hello', 'world')]
>>>


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

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

d = {key1 : value1, key2 : value2 }

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

值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

一个简单的字典实例:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

也可如此创建字典:

dict1 = { 'abc': 456 };

dict2 = { 'abc': 123, 98.6: 37 };

访问字典里的值

把相应的键放入熟悉的方括弧,如下实例:

实例

#!/usr/bin/python

 

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

 

print "dict['Name']: ", dict['Name'];

print "dict['Age']: ", dict['Age'];

以上实例输出结果:

dict['Name']:  Zara

dict['Age']:  7

如果用字典里没有的键访问数据,会输出错误如下:

实例

#!/usr/bin/python

 

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

 

print "dict['Alice']: ", dict['Alice'];

以上实例输出结果:

dict['Alice']: 

Traceback (most recent call last):

  File "test.py", line 5, in <module>

    print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

参考 http://blog.csdn.net/lemonwyc/article/details/40190111

 http://www.runoob.com/python/python-dictionary.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: