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 hashlib加密模块常用方法解析

这篇文章主要介绍了Python hashlib加密模块常用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 主要用于对字符串的加...

Python中的with语句与上下文管理器学习总结

0、关于上下文管理器 上下文管理器是可以在with语句中使用,拥有__enter__和__exit__方法的对象。 with manager as var: do_somethi...

django url到views参数传递的实例

一、采用?a=1&b=2访问 修改views.py: views.py from django.shortcuts import render from django.http im...

postman传递当前时间戳实例详解

postman传递当前时间戳实例详解

请求动态参数(例如时间戳) 有时我们在请求接口时,需要带上当前时间戳这种动态参数,那么postman能不能自动的填充上呢。 我们可以使用postman的pre-request scrip...

python实现爬山算法的思路详解

python实现爬山算法的思路详解

问题 找图中函数在区间[5,8]的最大值  重点思路 爬山算法会收敛到局部最优,解决办法是初始值在定义域上随机取乱数100次,总不可能100次都那么倒霉。 实现 imp...