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 我们从中挑选一些相对常用的方法来举例: 在上面的例子 ...
随机推荐
- Android 平台电容式触摸屏的驱动基本原理
Android 平台电容式触摸屏的驱动基本原理 Android 平台电容式触摸屏硬件基本原理 Linux 与 Android 的多点触摸协议 Linux输入子系统:事件的编码
- Python编程-网络编程
一.Socket复习 1.Socket参数 sk.bind(address) 必会 s.bind(address) 将套接字绑定到地址.address地址的格式取决于地址族.在AF_INET下,以元组 ...
- MySQL几个重要的目录
MySQL几个重要的目录 1 数据库目录 /var/lib/mysql/ 2 配置文件 /usr/share/mysql(mysql.server命令及配置文件) 3 相关命令 /usr/bin(my ...
- Docker 三剑客
Docker三剑客: Docker-Machine Docker Machine is a tool that lets you install Docker Engine on virtual ho ...
- EntityFramework 学习 一 Multiple Diagrams in Entity Framework 5.0
Visual Studio 2012 provides a facility to split the design time visual representation of the Entity ...
- Avoid RegionServer Hotspotting Despite Sequential Keys
n HBase world, RegionServer hotspotting is a common problem. We can describe this problem with a si ...
- JConsole操作手册
一篇Sun项目主页上介绍JConsole使用的文章,前段时间性能测试的时候大概翻译了一下以便学习,今天整理一下发上来,有些地方也不知道怎么翻,就保留了原文,可能还好理解点,呵呵,水平有限,翻的不好,大 ...
- UOJ67 新年的毒瘤
本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000 作者博客:http://www.cnblogs.com/ljh2000-jump/ ...
- App测试经验分享之登录注册
要诀 另外自己总结了一些要诀,仅供参考: 1)快:快速操作,营造冲突的场景,例如加载过程中返回键交互,快速点击登录按钮,快速切换菜单项,快速多次上下拉刷新 2)变:手机横竖屏.手机切换语言.手机调整字 ...
- 路由器分配的IP地址
在IP地址范围内,一部分地址将保留作为私人IP地址空间,专门用于内部局域网使用,这些地址如下表: A类 10.0.0.0-10.255.255.255 网络数:1 B类 172.16.0.0-172. ...