Python 基础之字典,dict的用法

python dict字典

字典是Python中唯一的内建映射类型,字典中的数据没有特定的顺序,可以通过特定的键(key)来存取数据。键可以是数字、元组或字符串,但不能是列表。

字典的常用方法:

1.1 clear()方法

1.2 copy()方法

1.3 fromkeys()方法

1.4 get()方法

1.5 has_key()方法

1.6 items、iteritems方法

1.7 keys、iterkeys

1.8 popitem()方法

1.9 setdefault()方法

1.10 update()方法

1.11 values、itervalues方法

字典的创建及存取数据操作:
1.1字面量创建
user_info={                     #创建字典
        "name":"james",
        "user_id":1122,
        "addr":"python home"
}
print user_info                                 #打印整个字典的数据
print user_info['name']                 #取user_info字典中,键为name的值
print user_info['addr']                 #取user_info字典中,键为addr的值
运行结果:
{'user_id': 1122, 'name': 'james', 'addr': 'python home'}
james
python home
[Finished in 0.1s]


1.2 dict()函数创建字典
list_user=[("name","Hugh"),("user_id",123456),("Hobby","python , java")]
print dict(list_user)                           #dict()函数创建字典
print dict(list_user)["name"]           #取生成字典后的键name的值
print dict(list_user)['Hobby']          #取生成字典后的键Hobby的值
运行结果:
{'Hobby': 'python , java', 'user_id': 123456, 'name': 'Hugh'}
Hugh
python , java
[Finished in 0.2s]

1.3 dict()函数创建字典
user_info=dict(name="Jason",age=18,Hobby="python,java")         #创建字典
print user_info
运行结果:
{'Hobby': 'python,java', 'age': 18, 'name': 'Jason'}
[Finished in 0.3s]

1.4 字典赋值
fruit={}                  #创建空字典
fruit['apple']="12.18"    #添加数据
fruit['banana']="0.89"
print fruit
运行结果:
{'apple': '12.18', 'banana': '0.89'}
[Finished in 0.2s]



字典的基础操作:
len()函数,用于返回字典中键-值对的数量(字典的长度)
color={'red':11,'blue':22,'green':33,'black':44,'White':55}
print len(color)   #获取color字典的长度
运行结果:
5

in 关键字,用于检查字典中是否存在指定的键(key)
color={'red':11,'blue':22,'green':33,'black':44,'White':55}
print 'red' in color      #检查red是否存在color字典中,存在则返回True,反之返回false
运行结果:
True

del 关键字,用于删除字典中指定的键-值对
color={'red':11,'blue':22,'green':33,'black':44,'White':55}
del color['blue']    #删除color中blue的键-值数据
print color
运行结果:
{'black': 44, 'White': 55, 'green': 33, 'red': 11}
[Finished in 0.2s]



clear()方法,用于清除字典中所有的项。
color={'red':11,'blue':22,'green':33,'black':44,'White':55}
color.clear()    #清除color中的所有项
print color
运行结果:
{}
[Finished in 0.2s]


copy()方法,用于复制字典
color={'red':11,'blue':22,'green':33,'black':44,'White':55}
copy_color=color.copy()
print copy_color
运行结果:
{'blue': 22, 'green': 33, 'White': 55, 'black': 44, 'red': 11}
[Finished in 0.1s]


fromkeys()方法,用于给定的键,建立新的字典,因此每个键都对应一个默认的值None。
print {}.fromkeys(['name','user_id','Hobby'])   #根据指定键,创建字典,默认值为None
运行结果:
{'Hobby': None, 'user_id': None, 'name': None}
[Finished in 0.1s]

print dict.fromkeys(['name','user_id','Hobby'])   ##根据指定键,创建字典,默认值为None
运行结果:
{'Hobby': None, 'user_id': None, 'name': None}
[Finished in 0.1s]

get()方法,用于访问字典项的方法,当访问一个不存在的键时,没有任何异常,而得到一个默认值None,也可以自定义默认值。
dict_a={}
print dict_a.get('name','not fount')     #获取dict_a字典name的值,找不到返回not fount
运行结果:
not fount
[Finished in 0.1s]


has_key()方法,用于检查特定的键(key)是否含有特定的键,与 in 关键字的效果差不多。
color={'red':11,'blue':22,'green':33,'black':44,'White':55}
print color.has_key("red")    #检查color中是否含有red键,如果找到则返回True,反之返回false
运行结果:
True
[Finished in 0.1s]


items、iteritems
item方法,用于将字典所有的项按列表的形式返回,iteritems与items差不过,不过iteritems返回的是一个迭代器。
items()方法
color={'red':11,'blue':22,'green':33,'black':44,'White':55}
print color.items()   #将字典转化为列表的形式
运行结果:
[('blue', 22), ('black', 44), ('White', 55), ('green', 33), ('red', 11)]
[Finished in 0.2s]

iteritems()方法
color={'red':11,'blue':22,'green':33,'black':44,'White':55}
print color.iteritems()   #将字典转化为列表的形式,返回一个迭代器
print list(color.iteritems())   #打印迭代器的数据
运行结果:
<dictionary-itemiterator object at 0x021405D0>    #迭代器
[('blue', 22), ('black', 44), ('White', 55), ('green', 33), ('red', 11)]
[Finished in 0.2s]


keys、iterkeys
keys方法,用于将字典中所有键转换为列表的形式,而iterkeys与keys差不多,不过iterkeys返回的是一个迭代器。
keys()方法
color={'red':11,'blue':22,'green':33,'black':44,'White':55}
print color.keys()   #将字典的所有键转化为列表的形式
运行结果:
['blue', 'black', 'White', 'green', 'red']
[Finished in 0.2s]

iterkeys()方法
color={'red':11,'blue':22,'green':33,'black':44,'White':55}
print color.iterkeys()   #将字典的所有键转化为列表的形式,返回一个迭代器
print list(color.iterkeys())   #打印迭代器的数据
运行结果:
<dictionary-keyiterator object at 0x021B05D0>
['blue', 'black', 'White', 'green', 'red']
[Finished in 0.2s]


popitem()方法,用于随机移除字典中项(键-值对),并返回被移除的项,因为字典中没有最后一项的说法,所有的项都是随机排序。
color={'red':11,'blue':22,'green':33,'black':44,'White':55}
print color.popitem()  #随机移除color中的一项,并返回移除的(键-值对)
print color
运行结果:
('blue', 22)
{'black': 44, 'White': 55, 'green': 33, 'red': 11}
[Finished in 0.2s]


setdefault()方法,用于获取字典指定键的值,与get方法类似,不过,如果字典中无该键,则将其添加到字典中。
user_info={}
print user_info.setdefault('name')   #获取user_info中的name,如果没有则将name添加到字典中,值默认为Nome
print user_info
运行结果:
None
{'name': None}
[Finished in 0.2s]

找不到指定键,添加后并给定默认值
user_info={}
print user_info.setdefault('Hobby','python') #如果获取不到Hobby,则将其添加到字典中,并给定值为:Python
print user_info
运行结果:
python
{'Hobby': 'python'}
[Finished in 0.2s]


update()方法,将一个字典更新到另一个字典中。
user_info={
        'name':'james',
        'user_id':'123456'
}
H={
        'Hobby':'python , java'
}
user_info.update(H) #将字典H中的项,添加到user_info中
print user_info
运行结果:
{'Hobby': 'python , java', 'user_id': '123456', 'name': 'james'}
[Finished in 0.3s]


values、itervalues
values方法,用于将字典中所有值转换为列表形式,itervalues与values差不多,但是,itervalues返回的是一个迭代器。
values方法
color={'red':11,'blue':22,'green':33,'black':44,'White':55}
print color.values()   #将字典中的所有值转换为列表
运行结果:
[22, 44, 55, 33, 11]
[Finished in 0.2s]

itervalues()方法
color={'red':11,'blue':22,'green':33,'black':44,'White':55}
print color.itervalues()   #将字典中的所有值转换为列表,返回一个迭代器
print list(color.itervalues())
运行结果:
<dictionary-valueiterator object at 0x021E05D0>
[22, 44, 55, 33, 11]
[Finished in 0.2s]