python实现在无须过多援引的情况下创建字典的方法

yipeiwu_com5年前Python基础

本文实例讲述了python实现在无须过多援引的情况下创建字典的方法。分享给大家供大家参考。具体实现方法如下:

1.使用itertools模块

import itertools
the_key = ['ab','22',33]
the_vale = ['aaaa',"dddddddd",'22222222222']
d = dict(itertools.izip(the_key,the_vale))
print d

2.加参数

dict = dict(red = 1,bule = 2,yellow = 3)
print dict

结果为:{'yellow': 3, 'bule': 2, 'red': 1}

3.使用内置的zip函数
zip([iterable,...])返回一个列表,

the_key = ['ab','22',33]
the_vale = ['aaaa',"dddddddd",'22222222222']
dict2 = dict(zip(the_key,the_vale))
print type(zip(the_key,the_vale))
print dict2

结果:

<type 'list'>
{33: '22222222222', 'ab': 'aaaa', '22': 'dddddddd'}

4.dict的fromkeys函数
创建的每个键有相同的value

fromkeys(seq[,value])
Create a new dictionary with keys from seq and values set to value.

the_key = ['ab','22',33]
the_vale = 0
d = dict.fromkeys(the_key,the_vale)
print 

结果:{33: 0, 'ab': 0, '22': 0}

import string
count_by_letter = dict.fromkeys(string.ascii_lowercase,0)
print count_by_letter

结果:

{'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0, 'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0, 't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0}

希望本文所述对大家Python程序设计的学习有所帮助。

相关文章

python文件操作之批量修改文件后缀名的方法

1、引言 需要把.dat 格式 转化成 .txt格式 2、实现 ##python批量更换后缀名 import os # 列出当前目录下所有的文件 files = os.listdir...

深入解析Python中的集合类型操作符

(1)标准类型操作符(所有的集合类型) 成员关系 (in, not in)         就序列而言,Python...

python在指定目录下查找gif文件的方法

本文实例讲述了python在指定目录下查找gif文件的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/python # Use the standard fin...

Python图片裁剪实例代码(如头像裁剪)

Python图片裁剪实例代码(如头像裁剪)

今天就来说个常用的功能,图片裁剪,可用于头像裁剪啊之类的。用的还是我们之前用的哪个模块pillow 1. 安装pillow 用pip安装 pip install pillow 2....

Python实现一个数组除以一个数的例子

如果直接用python的一个list除以一个数,会报错: a = [1.0, 1.0, 1.0] c = a/3 print(c) TypeError: unsupported...