python_在无须过多援引的情况下创建字典
2011-11-14 18:04
295 查看
1. 使用itertools模块
2. 加参数
结果为:{'yellow': 3, 'bule': 2, 'red': 1}
3.使用内置的zip函数
zip([iterable,...])返回一个列表,
<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.
结果:{33: 0, 'ab': 0, '22': 0}
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实现在无须过多援引的情况下创建字典的方法
- Python中创建字典的几种方法
- Python入门(4):创建和使用字典
- python-多种字典创建方式
- Python字典如何创建
- Python-Dictionary-创建字典的方式
- python字典2种的创建方法
- python字典的特性和字典得到创建与删除
- [Python]-01-创建有序字典
- python学习之创建和使用字典
- 使用python创建简单字典,并对其中的值进行更新。
- python字典的各种创建方法
- 解决python中遇到字典里key值为None的情况,取不出来的问题
- python 从字典里取出内容,创建集合 dict -> set
- python映射类型:字典---创建、更新、删除、修改等操作实例源码
- python创建和使用字典实例详解
- python的【字典dict】:创建、访问、更新、删除;查看键、值、键值对;遍历;排序
- Python利用{}.fromkeys来创建空字典的时候要注意附默认值时其他键会同时变化
- python创建关联数组(字典)的方法