python字典dictionary几个不常用函数例子

一、字典声明

如,d={};
d= {'x':1,'b':2}
d1 = dict(x=1,y=2,z=3)

    d2 = dict(a=3,b=4,c=5)

二 、方法说明:

参考:http://blog.csdn.net/wangran51/article/details/8440848
Operation Result Notes
len(a) the number of items in a 得到字典中元素的个数

 
a[k] the item of a with key k 取得键K所对应的值

(1), (10)
a[k] = v set a[k] to v 设定键k所对应的值成为v

 
del a[k] remove a[k] from a 从字典中删除键为k的元素

(1)
a.clear() remove all items from a 清空整个字典

 
a.copy() a (shallow) copy of a 得到字典副本

 
k in a True if a has a key k, else False 字典中存在键k则为返回True,没有则返回False

(2)
k not in a Equivalent to not k in a   字典中不存在键k则为返回true,反之返回False (2)
a.has_key(k) Equivalent to k in a, use that form in new code 等价于k in a  
a.items() a copy of a's list of (keyvalue) pairs 得到一个键,值的list (3)
a.keys() a copy of a's list of keys 得到键的list (3)
a.update([b]) updates (and overwrites) key/value pairs from b从b字典中更新a字典,如果键相同则更新,a中不存在则追加 (9)
a.fromkeys(seq[value]) Creates a new dictionary with keys from seq and values set to value 

(7)
a.values() a copy of a's list of values (3)
a.get(k[x]) a[k] if k in a, else x (4)
a.setdefault(k[x]) a[k] if k in a, else x (also setting it) (5)
a.pop(k[x]) a[k] if k in a, else x (and remove k) (8)
a.popitem() remove and return an arbitrary (keyvalue) pair (6)
a.iteritems() return an iterator over (keyvalue) pairs (2), (3)
a.iterkeys() return an iterator over the mapping's keys (2), (3)
a.itervalues() return an iterator over the mapping's values (2), (3)


注意:items(), keys(), values()都返回一个list,即[]
如:dict.items()输出为	[('a', 'b'), (1, 2), ('hello', 'world')]  

三、一些基本函数的使用code:

[wizad@sr104 lmj]$ vim test.py   

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[a]= apple

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'>

-------------

四、其他字典操作

#合并两个字典,无序

    1)直接通过dict()初始化实现

    d1 = dict(x=1,y=2,z=3)

    d2 = dict(a=3,b=4,c=5)

    print d1,d2

    

    d3 = dict(d1,**d2)

    #等同于 

    d3 = dict(d1,a=3,b=4,c=5)

    

    print d3

    输出为

        {'y': 2, 'x': 1, 'z': 3} {'a': 3, 'c': 5, 'b': 4}

        {'a': 3, 'c': 5, 'b': 4, 'y': 2, 'x': 1, 'z': 3}

    

    #dict()函数后面第一参数是dictionary,其他参数必须是多个展开的确定项如dict(d1,a=3,b=4,c=5),不能是dict,如果传入一个dict可以使用**kwargs传递,如 d3 = dict(d1,**{'a': 3, 'c': 5, 'b': 4})

#*args 和**kwargs

a)*args 和**kwargs做实参

传递整体对象匹配函数的多个形参,*args 没有key值,**kwargs有key值,*args用于list,**kwargs用于字典,如

        def fun_var_args_call(arg1, arg2, arg3):  

            print "arg1:", arg1  

            print "arg2:", arg2  

            print "arg3:", arg3  

      

        args = ["two", 3] #list  

        fun_var_args_call(1, *args)

        输出为:

            arg1: 1  

            arg2: two  

            arg3: 3  

b)*args 和**kwargs做形参:多余参数项收集器

而*args用函数的多余参数项为单个值的情况,将所有多余参数收集为list

        foo(*args,**kwargs):

            print 'args=',args

            print 'kwargs=',kwargs

        

        foo(1,2,3)

        输出为

            args= (1, 2, 3)

            kwargs= {}

        foo(1,2,3,a=1,b=2,c=3) 

        输出为

            args= (1, 2, 3)

            kwargs= {'a': 1, 'c': 3, 'b': 2}   







    2)字典的update函数实现:

    dict = {"a" : "apple", "b" : "banana"}

    print dict

    dict2 = {"c" : "grape", "d" : "orange"}

    dict.update(dict2)

    print dict

    3)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'}













#zip建立字典

    print zip(['a','b'],[1,2]) #返回list

    d = dict(zip([1,2],['a','b']))

    print d

    输出为:

        [('a', 1), ('b', 2)]

        {1: 'a', 2: 'b'}





#设置默认值

    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)使用:基本函数code实例,字典的合并、排序、copy,函数中*args 和**kwargs做形参和实参的更多相关文章

  1. Python中*args 和**kwargs作为形参和实参时的功能详解

    *args 和**kwargs作为形参 *args 和**kwargs作为形参被称为不定长参数,用来处理超出必备参数部分的参数.注意:args和kwargs可以修改为其它变量名. 必备参数就是在定义函 ...

  2. Python函数中*args和**kwargs来传递变长参数的用法

    参考自: http://www.jb51.net/article/78705.htm 单星号形式(*args)用来传递非命名键可变参数列表.双星号形式(**kwargs)用来传递键值可变参数列表. 1 ...

  3. Python中*args和**kwargs

    *args *args是可变的positional arguments列表 *args:将参数打包成元组(tuple)给函数调用 在函数中用 args 调用 **kwargs **kwargs是可变的 ...

  4. Python之路 day3 函数定义 *args及**kwargs

    #!/usr/bin/env python # -*- coding:utf-8 -*- #Author:ersa import time # def logger(): # time_format ...

  5. python 中*args 和 **kwargs

    简单的可以理解为python 中给函数传递的可变参数,args 是 列表的形式.kwargs 是 key,value的形式,也就是python 中的字典. *args 必须出现在**kwargs 的前 ...

  6. Python中 *args 和 **kwargs 的区别

    先来看个例子: def foo(*args, **kwargs): print 'args = ', args print 'kwargs = ', kwargs print '----------- ...

  7. python 中 *args he **kwargs的区别

    ''' 一 *args 和 **kwargs 的区别? *args 表示任意个 无名参数, 类型是元祖 tuple. **kwargs 表示的是关键字的参数 传入的参数是 dict 类型. 当*和** ...

  8. Python中*args 和**kwargs的用法

    当函数的参数不确定时,可以使用*args 和**kwargs,*args 没有key值,**kwargs有key值.还是直接来代码吧,废话少说[python] def fun_var_args(far ...

  9. 【Python】Python中*args 和**kwargs的用法

    好久没有学习Python了,应为工作的需要,再次拾起python,唤起记忆. 当函数的参数不确定时,可以使用*args 和**kwargs,*args 没有key值,**kwargs有key值. 还是 ...

随机推荐

  1. Java实现23种设计模式

    一.设计模式的分类 总体来说设计模式分为三大类: 创建型模式,共五种:工厂方法模式.抽象工厂模式.单例模式.建造者模式.原型模式. 结构型模式,共七种:适配器模式.装饰器模式.代理模式.外观模式.桥接 ...

  2. Spring cloud 学习资料整理

    推荐博客 纯洁的微笑 程序猿DD liaokailin的专栏 周立 Spring Cloud 方志朋 Spring Cloud 专栏 许进 跟我学Spring Cloud 推荐网站 Spring Cl ...

  3. C# 获取当前屏幕DPI

    1.通过Graphics类获取 Graphics currentGraphics = Graphics.FromHwnd(new WindowInteropHelper(mainWindow).Han ...

  4. Kinect2.0 MultiSourceFrameReader 的 AcquireLatestFrame 方法获取不到帧的解决方案

    先把大致要写的东西写一下,手里的活忙完了再完善. 在代码中使用下边的语句,获取Kinect中,colorFrame, depthFrame, bodyIndex三种帧,但是经常会遇到在后边的程序中处理 ...

  5. PHP 实例 AJAX 与 XML

    在 PHP 中,AJAX 可用来与 XML 文件进行交互式通信,具体的通信过程,请参考本文内容! AJAX XML 实例 下面的实例将演示网页如何通过 AJAX 从 XML 文件读取信息: 实例   ...

  6. SQLite Select 语句(http://www.w3cschool.cc/sqlite/sqlite-select.html)

    SQLite Select 语句 SQLite 的 SELECT 语句用于从 SQLite 数据库表中获取数据,以结果表的形式返回数据.这些结果表也被称为结果集. 语法 SQLite 的 SELECT ...

  7. Android Studio 使用wifi调试插件

    由于手机亦或是数据线的问题,在应用开发过程中会时不时地遇到手机突然连不上电脑的尴尬时刻,于是就学习了如何使用wifi进行应用调试.下面就具体介绍一下adb wifi插件的安装和使用.其实我们只需要安装 ...

  8. 通过一个例子了解MapReduce

    写MapReduce程序的步骤: 把问题转化为MapReduce模型: 设置运行参数: 写map类: 写reduce类: 例子:统计单词个数 Map的任务是将内容用" "分开,然后 ...

  9. android拍照获得图片及获得图片后剪切设置到ImageView

    ok,这次的项目需要用到设置头像功能,所以做了个总结,直接进入主题吧. 先说说怎么 使用android内置的相机拍照然后获取到这张照片吧 直接上代码: Intent intentFromCapture ...

  10. Java基本语法-----java函数

    函数的概述 发现不断进行加法运算,为了提高代码的复用性,就把该功能独立封装成一段独立的小程序,当下次需要执行加法运算的时候,就可以直接调用这个段小程序即可,那么这种封装形形式的具体表现形式则称作函数. ...