Python collections系列之默认字典
默认字典(defaultdict)
defaultdict是对字典的类型的补充,它默认给字典的值设置了一个类型。
1、创建默认字典
import collections dic = collections.defaultdict(list) # 设置dic的值类型为list
dic['k1'].append('evescn')
2、查看默认字典
print(dic) 输出结果:
defaultdict(<class 'list'>, {'k1': ['evescn']})
3、查看默认字典的方法
>>> dir(dic)
['__class__', '__contains__', '__copy__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__missing__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'default_factory', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
class defaultdict(dict):
"""
defaultdict(default_factory[, ...]) --> dict with default factory The default factory is called without arguments to produce
a new value when a key is not present, in __getitem__ only.
A defaultdict compares equal to a dict with the same items.
All remaining arguments are treated the same as if they were
passed to the dict constructor, including keyword arguments.
"""
def copy(self): # real signature unknown; restored from __doc__
""" D.copy() -> a shallow copy of D. """
pass def __copy__(self, *args, **kwargs): # real signature unknown
""" D.copy() -> a shallow copy of D. """
pass def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass def __init__(self, default_factory=None, **kwargs): # known case of _collections.defaultdict.__init__
"""
defaultdict(default_factory[, ...]) --> dict with default factory The default factory is called without arguments to produce
a new value when a key is not present, in __getitem__ only.
A defaultdict compares equal to a dict with the same items.
All remaining arguments are treated the same as if they were
passed to the dict constructor, including keyword arguments. # (copied from class doc)
"""
pass def __missing__(self, key): # real signature unknown; restored from __doc__
"""
__missing__(key) # Called by __getitem__ for missing key; pseudo-code:
if self.default_factory is None: raise KeyError((key,))
self[key] = value = self.default_factory()
return value
"""
pass def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass default_factory = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Factory for default value called by __missing__()."""
defaultdict
4、练习
有如下值集合 [11,22,33,44,55,66,77,88,99,90...],
将所有大于 66 的值保存至字典的第一个key中,
将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66 , 'k2': 小于66}
# 原生字典
values = [11, 22, 33,44,55,66,77,88,99,90] my_dict = {} for value in values:
if value>66:
if my_dict.has_key('k1'):
my_dict['k1'].append(value)
else:
my_dict['k1'] = [value]
else:
if my_dict.has_key('k2'):
my_dict['k2'].append(value)
else:
my_dict['k2'] = [value]
# 默认字典 from collections import defaultdict values = [11, 22, 33,44,55,66,77,88,99,90] my_dict = defaultdict(list) for value in values:
if value>66:
my_dict['k1'].append(value)
else:
my_dict['k2'].append(value) defaultdict字典解决方法
Python collections系列之默认字典的更多相关文章
- Python collections系列之有序字典
有序字典(orderedDict ) orderdDict是对字典类型的补充,他记住了字典元素添加的顺序 1.创建一个有序字典 import collections dic = collections ...
- Python collections系列之可命名元组
可命名元组(namedtuple) 根据nametuple可以创建一个包含tuple所有功能以及其他功能的类 1.创建一个坐标类 import collections # 创建类, defaultd ...
- Python collections系列之计数器
计数器(counter) Counter是对字典(无序)类型的补充,用于追踪值的出现次数. 使用counter需要导入 collections 类 ps:具备字典的所有功能 + 自己的功能 1.创建一 ...
- Python collections系列之单向队列
单向队列(deque) 单项队列(先进先出 FIFO ) 1.创建单向队列 import queue q = queue.Queue() q.put(') q.put('evescn') 2.查看单向 ...
- Python collections系列之双向队列
双向队列(deque) 一个线程安全的双向队列 1.创建一个双向队列 import collections d = collections.deque() d.append(') d.appendle ...
- collections系列之OrderedDict【有序字典】与DefaultDict【默认字典】
今天来向大家介绍一下collections系列中的OrderedDict和DefaultDict,这两种类均是通过collections来创建的,均是对dict字典加工,所有都继承了dict字典的方法 ...
- Python 第三篇(下):collections系列、集合(set)、单双队列、深浅copy、内置函数
一.collections系列: collections其实是python的标准库,也就是python的一个内置模块,因此使用之前导入一下collections模块即可,collections在py ...
- python递归、collections系列以及文件操作进阶
global log 127.0.0.1 local2 daemon maxconn log 127.0.0.1 local2 info defaults log global mode http t ...
- python基础知识4——collection类——计数器,有序字典,默认字典,可命名元组,双向队列
1.计数器(counter) Counter是对字典类型的补充,用于追踪值的出现次数. ps:具备字典的所有功能 + 自己的功能 Counter 我们从中挑选一些相对常用的方法来举例: 在上面的例子 ...
随机推荐
- 【leetcode刷题笔记】Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...
- vector对象
vector是模板而非类型,由vector生成的类型必须包含vector中元素的类型,例如vector<int> 定义和初始化vector对象: vector<T> v1 ...
- Kafka详解一:Kafka简介
问题导读 1.Kafka有何特性?2.Kafka有哪些组件? 背景: 当今社会各种应用系统诸如商业.社交.搜索.浏览等像信息工厂一样不断的生产出各种信息,在大数据时代,我们面临如下几个挑战: ...
- UVA 11186 Circum Triangle (枚举三角形优化)(转)
题意:圆上有n个点,求出这n个点组成的所有三角形的面积之和 题解: 当我们要求出S(i,j,k)时,我们需要假设k在j的左侧,k在i与j之间,k在i的右侧. 如果k在 j的左侧 那么 S(i,j,k ...
- QT 实现按住鼠标左键点击对话框空白处,拖动对话框
定义头文件 QPoint move_point; //移动的距离 bool mouse_press; //按下鼠标左键 protected: void mousePressEvent( ...
- QT 中一些数学计算函数
QT的一些範例中有出現 qmax, qmin 等 math函式的身影,但我在官方文件中卻找不到與 math函式相關的說明,所以我就把函式的source裡面提供的方法整理條列,並且看看還有哪些 math ...
- 虚拟机CentOS6.5网络配置
不得不说 6.5比7.0麻烦了许多.. 编辑ifcfg配置文件 vi /etc/sysconfig/network-script/ifcfg-eth0 内容如下 DEVICE=eth0 HWADDR ...
- Java中各种集合特点总结
1:集合: (1) Collection(单列集合) List(有序,可重复) ArrayList 底层数据结构是数组,查 ...
- underscore中template的使用Demo
在客户端渲染数据时,一般可通过underscore中的template对数据模板进行渲染,例如: 定义模板,需要把type类型设置为“text/template” <script type=&q ...
- php 策略模式案例
策略模式,将一组特定的行为和算法封装成类,以适应某些特定的上下文环境. eg:假如有一个电商网站系统,针对男性女性用户要各自跳转到不同的商品类目,并且所有的广告位展示不同的广告.在传统的代码中,都是在 ...