首页 > 代码库 > python字典(dictionary)使用:不常用的基本函数例子
python字典(dictionary)使用:不常用的基本函数例子
|
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for k in dict:
print "dict[%s]="%k,dict[k]
key="c"
if "c" not in dict:
print "it is not in %s" %key
print "-------------"
print dict.items()
print dict.keys()
print dict.values()
print "-------------"
iter = dict.iteritems()
for it in iter:
print "iteritems is:",it
print type(it)
print "-------------"
key_iter = dict.iterkeys()
for ki in key_iter:
print "key_iter is",ki
print type(ki)
print "-------------"
val_iter = dict.itervalues()
for vi in val_iter:
print "val_iter is",vi
print type(vi)
print "-------------"
dict[b]= banana
dict[o]= orange
dict[g]= grape
it is not in c
-------------
[(‘a‘, ‘apple‘), (‘b‘, ‘banana‘), (‘o‘, ‘orange‘), (‘g‘, ‘grape‘)]
[‘a‘, ‘b‘, ‘o‘, ‘g‘]
[‘apple‘, ‘banana‘, ‘orange‘, ‘grape‘]
-------------
iteritems is: (‘a‘, ‘apple‘)
<type ‘tuple‘>
iteritems is: (‘b‘, ‘banana‘)
<type ‘tuple‘>
iteritems is: (‘o‘, ‘orange‘)
<type ‘tuple‘>
iteritems is: (‘g‘, ‘grape‘)
<type ‘tuple‘>
-------------
key_iter is a
<type ‘str‘>
key_iter is b
<type ‘str‘>
key_iter is o
<type ‘str‘>
key_iter is g
<type ‘str‘>
-------------
val_iter is apple
<type ‘str‘>
val_iter is banana
<type ‘str‘>
val_iter is orange
<type ‘str‘>
val_iter is grape
<type ‘str‘>
-------------
#字典的update:合并两个字典,无序
dict = {"a" : "apple", "b" : "banana"}
print dict
dict2 = {"c" : "grape", "d" : "orange"}
dict.update(dict2)
print dict
#udpate()的等价语句
D = {"key1" : "value1", "key2" : "value2"}
E = {"key3" : "value3", "key4" : "value4"}
for k in E:
D[k] = E[k]
print D
输出:
{‘key3‘: ‘value3‘, ‘key2‘: ‘value2‘, ‘key1‘: ‘value1‘, ‘key4‘: ‘value4‘}
#设置默认值
dict = {}
dict.setdefault("a")
print dict
dict["a"] = "apple"
dict.setdefault("a","default")
print dict
#调用sorted()排序
dict = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"}
print dict
#按照key排序
print sorted(dict.items(), key=lambda d: d[0])
#按照value排序
print sorted(dict.items(), key=lambda d: d[1])
#字典的浅拷贝
dict = {"a" : "apple", "b" : "grape"}
dict2 = {"c" : "orange", "d" : "banana"}
dict2 = dict.copy()
print dict2
#字典的深拷贝
import copy
dict = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}}
dict2 = copy.deepcopy(dict)
dict3 = copy.copy(dict)
dict2["b"]["g"] = "orange"
print dict
dict3["b"]["g"] = "orange"
print dict
python字典(dictionary)使用:不常用的基本函数例子