举例如下:
1、新增python文件,testdictkeypy;
my_dict = dict(name="lili", age=32, money=1200, hourse=None)
key_list = my_dictkeys()
print(list(key_list))
3、选择‘在终端中运行Python文件’;
4、查看运行结果,可以输出字典的所有键;['name', 'age', 'money', 'hourse']
1
获取文件后缀名:
复制代码代码如下:
#!/usr/bin/python
import
os
dict
=
{}
for
d,
fd,
fl
in
oswalk('/home/ahda/Program/'):
for
f
in
fl:
sufix
=
ospathsplitext(f)[1][1:]
if
dicthas_key(sufix):
dict[sufix]
+=
1
else:
dict[sufix]
=
1
for
item
in
dictitems():
"%s
:
%s"
%
item
这里的关键是ospathsplitext()
如abc/efgh
,这里获取到的是h
2
python查找遍历指定文件路径下指定后缀名的文件实例:
复制代码代码如下:
import
os
import
sys
import
ospath
for
dirpath,
dirnames,
filenames
in
oswalk(startdir):
for
filename
in
filenames:
if
ospathsplitext(filename)[1]
==
'txt':
filepath
=
ospathjoin(dirpath,
filename)
#print("file:"
+
filepath)
input_file
=
open(filepath)
text
=
input_fileread()
input_fileclose()
output_file
=
open(
filepath,
'w')
output_filewrite(text)
output_fileclose()
3
批量重命名目录中的文件后缀实例:
复制代码代码如下:
import
os
def
swap_extensions(dir,
before,
after):
if
before[:1]
!=
'':
#如果参数中的后缀名没有''则加上
before
=
''
+
before
thelen
=
-len(before)
if
after[:1]
!=
'':
after
=
''
+
after
for
path,
subdir,
files
in
oswalk(dir):
for
oldfile
in
files:
if
oldfile[thelen:]
==
before:
oldfile
=
ospathjoin(path,
oldfile)
newfile
=
oldfile[:thelen]
+
after
osrename(oldfile,
newfile)
oldfile
+'
changed
to
'
+
newfile
if
__name__
==
'__main__':
import
sys
if
len(sysargv)
!=
4:
'Usage:swap_extensionpy
rootdir
before
after'
sysexit(1)
swap_extensions(sysargv[1],
sysargv[2],
sysargv[3])
例子:将e:/py/test目录下php结尾的文件重命名为py
E:py>python_cook
e:/py/test
php
py
e:/py/testtestphp
changed
to
e:/py/testtestpy
e:/py/test1php
changed
to
e:/py/test1py
e:/py/test2php
changed
to
e:/py/test2py
city_menu={"BJ":{"dongcheng":{"size":4184,"people":919,"code":100010},
"xicheng":{"size":5070,"people":1243,"code":100032},
"chaoyang":{"size":4708,"people":3083,"code":100020}},
"GZ":{"yuexiu":{"size":3380,"people":115,"code":510030},
"liwan":{"size":5910,"Mpeople":89,"code":510145},
"tianhe":{"size":9633,"people":143,"code":510630},
"haizhu":{"size":9040,"people":155,"code":510220}},
"SZ":{"futian":{"size":7866,"people":13571,"code":518000},
"nanshan":{"size":18549,"people":11359,"code":518000},
"luohu":{"size":7876,"people":9537,"code":518001}}}
d={}
for k0,v0 in city_menuitems():
for k1,v1 in v0items():
d[v1['code']]=k0+"-"+k1
def city():
qu=input('请输入邮政编码:')
if int(qu) in d:
return print('邮政编码为:%s 的城市是%s。' %(qu,d[int(qu)]))
else:
print('输入错误!')
items()返回的是列表对象,而iteritems()返回的是iterator对象。例如:
print dicitems() #[('a', 'hello'), ('c', 'you'), ('b', 'how')]
print diciteritems() #<dictionary-itemiterator object at 0x020E9A50>
深究:iteritor是迭代器的意思,一次反悔一个数据项,知道没有为止
for i in diciteritems():
print i
结果:('a', 'hello')
('c', 'you')
('b', 'how')
以上就是关于python中怎么取出字典的键全部的内容,包括:python中怎么取出字典的键、python如何获取上传图片后缀名、python中如何取嵌套字典中的多个值等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)