python3之dict字典
字典字典是一种无序结构字典是一种kv结构value可以是任何对象key是唯一的key必须是可hash对象
字典初始化
d = {}d = dict()d = {'a':1 , 'b':2}
字典的方法:
1. d.clear
##删除字典dict中的所有元素,返回noneIn : d ={'a': 1, 'b': 2}In : d.clear()In : dOut: {}
2. d.fromkeys
## fromkeys()方法从序列键和值设置为value来创建一个新的字典。例:#!/usr/bin/pythonseq = ('name', 'age', 'sex')dict = dict.fromkeys(seq)print "New Dictionary : %s" %str(dict)dict = dict.fromkeys(seq, 10)print "New Dictionary : %s" %str(dict)
输出:
New Dictionary : {'age': None, 'name': None, 'sex': None}New Dictionary : {'age': 10, 'name': 10, 'sex': 10}3. d.items
##返回字典的(键,值)元组对的列表例:In : d ={'a': 1, 'b': 2}In : d.items()Out: dict_items([('b', 2), ('a', 1)])4. d.pop
##d.pop( x ) 返回给定键 x 对应的值,并将该键值对从字典中删除列:In : dOut: {'a': 1, 'b': 2}In : d.pop('a')Out: 1
5. d.setdefault
## d.setdefault( x, [ , y ] )返回字典 d 中键 x 对应的值,若键 x 不存在,则返回y, 并将 x : y 作为键值对添加到字典中,y 的默认值为 None例:>>> d = {'z': 5, 'x': 1.5, 'y': 3}>>> d.setdefault('x')1.5>>> del d['x']>>> d.setdefault('x','Look!')'Look!'>>> d{'z': 5, 'x': 'Look!', 'y': 3}
6. d.values
##返回字典dict的值列表In : dOut: {'a': 1, 'b': 2}
In : for v in d.values(): .....: print(v) .....:21
7. d.copy
##返回字典dict的浅表副本In : dOut: {'a': 1, 'b': 2}In : d1 = d.copy()In : d1Out: {'a': 1, 'b': 2} 8. d.get
## get()方法返回给定键的值。如果键不可用,则返回默认值None。例:#!/usr/bin/pythondict = {'Name': 'Zara', 'Age': 27}print "Value : %s" %dict.get('Age')print "Value : %s" %dict.get('Sex', "Never")输出:Value : 27Value : Never
9. d.keys
##返回字典的键的列表例:#!/usr/bin/pythondict ={'Name':'Zara','Age':7}print"Value : %s"%dict.keys()输出:Value : ['Age', 'Name']
10.d.popitem
## d.popitem( ) 返回并删除字典 d 中随机的键值对例:>>> d = {'z': 5, 'x': 1.5, 'y': 3}>>> d.popitem()('z', 5)>>> d.popitem()('x', 1.5)
11.d.update
##d.update( x ) 将字典 x 所有键值对添加到字典 d 中(不重复,重复的键值对用字典 x 中的键值对替代字典 d 中)例:>>> d1 = {'x':1, 'y':3}>>> d2 = {'x':2, 'z':1.4}>>> d1.update(d2)>>> d1{'z': 1.4, 'x': 2, 'y': 3}
页:
[1]