python的key函数 python keys方法

python 内置排序函数使用

python内置关于排序的工具主要有两个一个是列表自带的 sort() 方法,另外一个是 sorted() 函数。Python 列表内置方法可以直接修改列表。而 sorted() 内置函数从一个可迭代对象(列表,元组等都可以)构建一个新的排序列表。其函数原型分别如下:

创新互联公司云计算的互联网服务提供商,拥有超过13年的服务器租用、达州托管服务器、云服务器、雅安服务器托管、网站系统开发经验,已先后获得国家工业和信息化部颁发的互联网数据中心业务许可证。专业提供云主机、雅安服务器托管域名注册、VPS主机、云服务器、香港云服务器、免备案服务器等。

对列表进行默认排序

从函数原型来看,可以看到两者都具有两个可选参数,它们都必须指定为关键字参数。

key 指定带有单个参数的函数,用于从 iterable 的每个元素中提取用于比较的键 (例如 key=str.lower)。默认值为 None (直接比较元素)。 key 形参的值应该是个函数(或其他可调用对象),它接受一个参数并返回一个用于排序的键。

假设有其他类型的变量,比如一个自定义的类或者列表中又是一个列表。以官网例子为例有这样一个列表,其元素为元组,

可以用以下方式按照年龄排序

类似的有自定义类

可以用如下方式进行排序

也可以显示定义一个函数,且只有一个参数,返回用于排序的键,比如

总之就是定义一个函数返回一个用于排序的键,可以用lambda函数或者 def 定义都可以。

上面实现的简单函数实际就是实现了返回一个有序结构的第 n 的元素,或者某个类中的某个属性,因此 Python 提供了便利功能,使访问器功能更容易,更快捷。operator 模块有 itemgetter() 、 attrgetter() 函数。分别完成返回第 n 个元素,某个属性功能。上面的排序可以用如下方式进行实现

在python2中,sort有一个 cmp 参数,即用一个函数来自定义比较,在python3中这种方式被取消。为了继承类似的用法,在 Python 3.2 中, functools.cmp_to_key() 函数被添加到标准库中的 functools 模块中。

这种作用先定义如何比较两个变量,以上面的学生列表按照年龄排序为例

这种做法自定义比较函数接收两个形参,返回比较结果(bool),而新式方法接受一个参数,返回的是比较的键。

假设有字典 d = {'b':2, 'a':1,'c':8,'d':4} ,则可以通过以下方式对字典按照键和值进行排序

python中利用dict的key()函数读取键,构造新的list?

dict_key(list)不是一种结构,而是一个dict_key类

这是一个不支持索引的,你可以通过

print(type(data.keys())来查看该类,

如果你需要一个list的key值 ,你可以通过list(data.keys())的方式获取一个可索引的列表

python中的keys()函数有什么作用?

keys返回的是包含所有键的一个列表,而字典名本身代表字典这个对象。之所以for循环能直接作用于字典名上是因为字典类中实现了iter()方法,它会返回一个迭代器,这个迭代器能逐一返回字典中的每个键。

python 字典是否有key

第一种方法:使用自带函数实现。

在python的字典的属性方法里面有一个has_key()方法,这个方法使用起来非常简单。

例:

#生成一个字典d = {'name':{},'age':{},'sex':{}}#打印返回值print d.has_key('name')#结果返回True

第二种方法:使用in方法

#生成一个字典d = {'name':{},'age':{},'sex':{}}#打印返回值,其中d.keys()是列出字典所有的keyprint name in d.keys()#结果返回True

上面两种方式,我更推荐使用第二种,因为has_key()是python2.2之前的方法,而且使用in的方法会更快一些。

最后告诉大家一点:除了使用in还可以使用not in,判定这个key不存在哦~

python字典操作函数

字典是一种通过名字或者关键字引用的得数据结构,其键可以是数字、字符串、元组,这种结构类型也称之为映射。字典类型是Python中唯一内建的映射类型,基本的操作包括如下:

(1)len():返回字典中键—值对的数量;

(2)d[k]:返回关键字对于的值;

(3)d[k]=v:将值关联到键值k上;

(4)del d[k]:删除键值为k的项;

(5)key in d:键值key是否在d中,是返回True,否则返回False。

(6)clear函数:清除字典中的所有项

(7)copy函数:返回一个具有相同键值的新字典;deepcopy()函数使用深复制,复制其包含所有的值,这个方法可以解决由于副本修改而使原始字典也变化的问题

(8)fromkeys函数:使用给定的键建立新的字典,键默认对应的值为None

(9)get函数:访问字典成员

(10)has_key函数:检查字典中是否含有给出的键

(11)items和iteritems函数:items将所有的字典项以列表方式返回,列表中项来自(键,值),iteritems与items作用相似,但是返回的是一个迭代器对象而不是列表

(12)keys和iterkeys:keys将字典中的键以列表形式返回,iterkeys返回键的迭代器

(13)pop函数:删除字典中对应的键

(14)popitem函数:移出字典中的项

(15)setdefault函数:类似于get方法,获取与给定键相关联的值,也可以在字典中不包含给定键的情况下设定相应的键值

(16)update函数:用一个字典更新另外一个字典

(17) values和itervalues函数:values以列表的形式返回字典中的值,itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重复的元素

一、字典的创建

1.1 直接创建字典

d={'one':1,'two':2,'three':3}

printd

printd['two']

printd['three']

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

1.2 通过dict创建字典

# _*_ coding:utf-8 _*_

items=[('one',1),('two',2),('three',3),('four',4)]

printu'items中的内容:'

printitems

printu'利用dict创建字典,输出字典内容:'

d=dict(items)

printd

printu'查询字典中的内容:'

printd['one']

printd['three']

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

items中的内容:

[('one',1), ('two',2), ('three',3), ('four',4)]

利用dict创建字典,输出字典内容:

{'four':4,'three':3,'two':2,'one':1}

查询字典中的内容:

或者通过关键字创建字典

# _*_ coding:utf-8 _*_

d=dict(one=1,two=2,three=3)

printu'输出字典内容:'

printd

printu'查询字典中的内容:'

printd['one']

printd['three']

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

输出字典内容:

{'three':3,'two':2,'one':1}

查询字典中的内容:

二、字典的格式化字符串

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3,'four':4}

printd

print"three is %(three)s."%d

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'four':4,'three':3,'two':2,'one':1}

threeis3.

三、字典方法

3.1 clear函数:清除字典中的所有项

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3,'four':4}

printd

d.clear()

printd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'four':4,'three':3,'two':2,'one':1}

{}

请看下面两个例子

3.1.1

# _*_ coding:utf-8 _*_

d={}

dd=d

d['one']=1

d['two']=2

printdd

d={}

printd

printdd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'two':2,'one':1}

{}

{'two':2,'one':1}

3.1.2

# _*_ coding:utf-8 _*_

d={}

dd=d

d['one']=1

d['two']=2

printdd

d.clear()

printd

printdd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'two':2,'one':1}

{}

{}

3.1.2与3.1.1唯一不同的是在对字典d的清空处理上,3.1.1将d关联到一个新的空字典上,这种方式对字典dd是没有影响的,所以在字典d被置空后,字典dd里面的值仍旧没有变化。但是在3.1.2中clear方法清空字典d中的内容,clear是一个原地操作的方法,使得d中的内容全部被置空,这样dd所指向的空间也被置空。

3.2 copy函数:返回一个具有相同键值的新字典

# _*_ coding:utf-8 _*_

x={'one':1,'two':2,'three':3,'test':['a','b','c']}

printu'初始X字典:'

printx

printu'X复制到Y:'

y=x.copy()

printu'Y字典:'

printy

y['three']=33

printu'修改Y中的值,观察输出:'

printy

printx

printu'删除Y中的值,观察输出'

y['test'].remove('c')

printy

printx

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

初始X字典:

{'test': ['a','b','c'],'three':3,'two':2,'one':1}

X复制到Y:

Y字典:

{'test': ['a','b','c'],'one':1,'three':3,'two':2}

修改Y中的值,观察输出:

{'test': ['a','b','c'],'one':1,'three':33,'two':2}

{'test': ['a','b','c'],'three':3,'two':2,'one':1}

删除Y中的值,观察输出

{'test': ['a','b'],'one':1,'three':33,'two':2}

{'test': ['a','b'],'three':3,'two':2,'one':1}

注:在复制的副本中对值进行替换后,对原来的字典不产生影响,但是如果修改了副本,原始的字典也会被修改。deepcopy函数使用深复制,复制其包含所有的值,这个方法可以解决由于副本修改而使原始字典也变化的问题。

# _*_ coding:utf-8 _*_

fromcopyimportdeepcopy

x={}

x['test']=['a','b','c','d']

y=x.copy()

z=deepcopy(x)

printu'输出:'

printy

printz

printu'修改后输出:'

x['test'].append('e')

printy

printz

运算输出:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

输出:

{'test': ['a','b','c','d']}

{'test': ['a','b','c','d']}

修改后输出:

{'test': ['a','b','c','d','e']}

{'test': ['a','b','c','d']}

3.3 fromkeys函数:使用给定的键建立新的字典,键默认对应的值为None

# _*_ coding:utf-8 _*_

d=dict.fromkeys(['one','two','three'])

printd

运算输出:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':None,'two':None,'one':None}

或者指定默认的对应值

# _*_ coding:utf-8 _*_

d=dict.fromkeys(['one','two','three'],'unknow')

printd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':'unknow','two':'unknow','one':'unknow'}

3.4 get函数:访问字典成员

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

printd.get('one')

printd.get('four')

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

1

None

注:get函数可以访问字典中不存在的键,当该键不存在是返回None

3.5 has_key函数:检查字典中是否含有给出的键

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

printd.has_key('one')

printd.has_key('four')

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

True

False

3.6 items和iteritems函数:items将所有的字典项以列表方式返回,列表中项来自(键,值),iteritems与items作用相似,但是返回的是一个迭代器对象而不是列表

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

list=d.items()

forkey,valueinlist:

printkey,':',value

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

three :3

two :2

one :1

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

it=d.iteritems()

fork,vinit:

print"d[%s]="%k,v

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

d[three]=3

d[two]=2

d[one]=1

3.7 keys和iterkeys:keys将字典中的键以列表形式返回,iterkeys返回键的迭代器

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

printu'keys方法:'

list=d.keys()

printlist

printu'\niterkeys方法:'

it=d.iterkeys()

forxinit:

printx

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

keys方法:

['three','two','one']

iterkeys方法:

three

two

one

3.8 pop函数:删除字典中对应的键

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

d.pop('one')

printd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

{'three':3,'two':2}

3.9 popitem函数:移出字典中的项

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

d.popitem()

printd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':1}

{'two':2,'one':1}

3.10 setdefault函数:类似于get方法,获取与给定键相关联的值,也可以在字典中不包含给定键的情况下设定相应的键值

# _*_ coding:utf-8 _*_

d={'one':1,'two':2,'three':3}

printd

printd.setdefault('one',1)

printd.setdefault('four',4)

printd

运算结果:

{'three':3,'two':2,'one':1}

{'four':4,'three':3,'two':2,'one':1}

3.11 update函数:用一个字典更新另外一个字典

# _*_ coding:utf-8 _*_

d={

'one':123,

'two':2,

'three':3

}

printd

x={'one':1}

d.update(x)

printd

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

{'three':3,'two':2,'one':123}

{'three':3,'two':2,'one':1}

3.12 values和itervalues函数:values以列表的形式返回字典中的值,itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重复的元素

# _*_ coding:utf-8 _*_

d={

'one':123,

'two':2,

'three':3,

'test':2

}

printd.values()

运算结果:

=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======

[2,3,2,123]

Python字典中几个常用函数总结

1、get() 返回指定键的值,如果值不在字典中返回default值。

语法:dict.get(key,default=None)

参数:

key 字典中要查找的键。

default 如果指定键的值不存在时,返回该默认值值。

例:

dict={'Name':'alex','Age':21}

print("Name is:%s"% dict.get('Name')+"\n"+ "Age is:%d"% dict.get('Age'))

显示结果为:

Name is:alex

Age is:21

2、update() 将一个字典中的值更新到另一个字典中。

语法:dict.update(dict2)

参数:

dict2 添加到指定字典dict里的字典。

例:

dict={'Name':'alex','Age':21}

dict2={'Sex':'female'}

dict.update(dict2)

print("Value is %s" % dict)

显示结果为:

Value is {'Name': 'alex', 'Age': 21, 'Sex': 'female'}


当前文章:python的key函数 python keys方法
网站地址:http://scyanting.com/article/doooihs.html