python字典(dictionary)使用:基本函数code实例,字典的合并、排序、copy,函数中*args 和**kwargs做形参和实参
一、字典声明
d2 = dict(a=3,b=4,c=5)
二 、方法说明:
|
注意:items(), keys(), values()都返回一个list,即[]
如:dict.items()输出为 [('a', 'b'), (1, 2), ('hello', 'world')]
三、一些基本函数的使用code:
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'>
-------------
四、其他字典操作
#合并两个字典,无序
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做实参
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做形参和实参的更多相关文章
- Python中*args 和**kwargs作为形参和实参时的功能详解
*args 和**kwargs作为形参 *args 和**kwargs作为形参被称为不定长参数,用来处理超出必备参数部分的参数.注意:args和kwargs可以修改为其它变量名. 必备参数就是在定义函 ...
- Python函数中*args和**kwargs来传递变长参数的用法
参考自: http://www.jb51.net/article/78705.htm 单星号形式(*args)用来传递非命名键可变参数列表.双星号形式(**kwargs)用来传递键值可变参数列表. 1 ...
- Python中*args和**kwargs
*args *args是可变的positional arguments列表 *args:将参数打包成元组(tuple)给函数调用 在函数中用 args 调用 **kwargs **kwargs是可变的 ...
- Python之路 day3 函数定义 *args及**kwargs
#!/usr/bin/env python # -*- coding:utf-8 -*- #Author:ersa import time # def logger(): # time_format ...
- python 中*args 和 **kwargs
简单的可以理解为python 中给函数传递的可变参数,args 是 列表的形式.kwargs 是 key,value的形式,也就是python 中的字典. *args 必须出现在**kwargs 的前 ...
- Python中 *args 和 **kwargs 的区别
先来看个例子: def foo(*args, **kwargs): print 'args = ', args print 'kwargs = ', kwargs print '----------- ...
- python 中 *args he **kwargs的区别
''' 一 *args 和 **kwargs 的区别? *args 表示任意个 无名参数, 类型是元祖 tuple. **kwargs 表示的是关键字的参数 传入的参数是 dict 类型. 当*和** ...
- Python中*args 和**kwargs的用法
当函数的参数不确定时,可以使用*args 和**kwargs,*args 没有key值,**kwargs有key值.还是直接来代码吧,废话少说[python] def fun_var_args(far ...
- 【Python】Python中*args 和**kwargs的用法
好久没有学习Python了,应为工作的需要,再次拾起python,唤起记忆. 当函数的参数不确定时,可以使用*args 和**kwargs,*args 没有key值,**kwargs有key值. 还是 ...
随机推荐
- EF实体的部分更新
实现实体的部分更新假设实体InfoHotel如下: public class InfoHotel { public int Id{get;set;} public string Name{get;se ...
- React-报错Warning:setState(...)on anunmounted component
一.原因 这种错误一般出现在react组件已经从DOM中移除.我们在react组件中发送一些异步请求的时候,就可能会出现这样的问题.举个例子,我们在componentWillMount中 ...
- LINUX逻辑卷(LVM)管理与逻辑卷分区
LINUX之逻辑卷管理与逻辑卷扩展 LVM是逻辑卷管理(Logical Volume Manager)的简称,他是建立在物理存储设备之上的一个抽象层,允许你生成逻辑存储卷,和直接使用物理存储在管理上相 ...
- JavaScript正则表达式模式匹配(3)——贪婪模式和惰性模式
var pattern=/[a-z]+/; //这里使用了贪婪模式, var str='abcdefg'; alert(str.replace(pattern,'1')); //所有的字符串变成了1 ...
- Linux 管理软件
公司的openfire先前运行在windows上的,但由于在windows上openfire内存机制问题,最多只能占用2GB内存,且时间稍微长久一些就会自动挂掉,用户无法登陆和连接,因此迁移到了Cen ...
- 一些重要的计算机网络协议(IP、TCP、UDP、HTTP)
一.计算机网络的发展历程 1.计算机网络发展 与其说计算机改变了世界,倒不如说是计算机网络改变了世界.彼时彼刻,你我都因网络而有了交集,岂非一种缘分? 计算机与网络发展大致经历如下过程:
- js简单备忘录
<section class="myMemory"> <h3 class="f-tit">记事本</h3> <div ...
- 利用JAVA多线程来提高数据处理效率
肿瘤大数据挖掘中经常需要处理上百亿行的文本文件,这些文件往往高达数百GB,假如文件结构简单统一,那么用sed和awk 处理是非常方便和快速的.但有时候会遇到逻辑较为复杂的处理流程,这样我一般会用JAV ...
- Node.js 实用工具
稳定性: 4 - 锁定 这些函数都在'util' 模块里.使用 require('util') 来访问他们. util 模块原先设计的初衷是用来支持 node 的内部 API 的.这里的很多的函数对你 ...
- JavaScript If…Else 语句
条件语句用于基于不同的条件来执行不同的动作. 条件语句 通常在写代码时,您总是需要为不同的决定来执行不同的动作.您可以在代码中使用条件语句来完成该任务. 在 JavaScript 中,我们可使用以下条 ...