python 字典不区分大小写工具类
# -*- coding: utf-8 -*-
# @Time : 2018/12/20 4:28 PM
# @Author : cxa
# @File : DictHelper.py
# @Software: PyCharm
# -*- coding: utf-8 -*-
# @Time : 2018/10/16 10:34
# @Author : cxa
# @File : dictMethod.py
# @Software: PyCharm
# -*- coding: utf-8 -*-
"""
requests.structures
~~~~~~~~~~~~~~~~~~~
Data structures that power Requests.
"""
from collections import OrderedDict
from collections.abc import Mapping, MutableMapping, Iterable
class CaseInsensitiveDict(MutableMapping):
"""A case-insensitive ``dict``-like object.
Implements all methods and operations of
``MutableMapping`` as well as dict's ``copy``. Also
provides ``lower_items``.
All keys are expected to be strings. The structure remembers the
case of the last key to be set, and ``iter(instance)``,
``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
will contain case-sensitive keys. However, querying and contains
testing is case insensitive::
cid = CaseInsensitiveDict()
cid['Accept'] = 'application/json'
cid['aCCEPT'] == 'application/json' # True
list(cid) == ['Accept'] # True
For example, ``headers['content-encoding']`` will return the
value of a ``'Content-Encoding'`` response header, regardless
of how the header name was originally stored.
If the constructor, ``.update``, or equality comparison
operations are given keys that have equal ``.lower()``s, the
behavior is undefined.
"""
def __init__(self, data=None, **kwargs):
# 初始化的时候进入,初始化一个 OrderedDict()
self._store = OrderedDict()
if data is None:
data = {}
self.update(data, **kwargs) # 把属性加入到 self 的__dict__里,也是一个字典操作。
def __setitem__(self, key, value):
# key.lower() 把字符串转换成小写
# 这句话在属性赋值的时候会被调用。实现的无视字母大小写进行赋值
self._store[key.lower()] = (key, value)
# setattr(self,key.lower(),(key, value))
def __getitem__(self, key):
return self._store[key.lower()][1]
def __delitem__(self, key):
del self._store[key.lower()]
def __iter__(self):
return (casedkey for casedkey, mappedvalue in self._store.values()) # 调用父类的__iter__
def __len__(self):
return len(self._store)
def lower_items(self):
"""Like iteritems(), but with all lowercase keys."""
return (
(lowerkey, keyval[1])
for (lowerkey, keyval)
in self._store.items()
)
def __eq__(self, other):
if isinstance(other, Mapping):
other = CaseInsensitiveDict(other)
else:
return NotImplemented
# Compare insensitively
return dict(self.lower_items()) == dict(other.lower_items())
# Copy is required
def copy(self):
return CaseInsensitiveDict(self._store.values())
def __repr__(self):
# print 的时候会进入
print(isinstance(self.items(), Iterable)) # 输入可迭代对象,此时
##内部实际
# dict(iterable)
# d = {}
# for k, v in iterable: #会调用__iter__
# d[k] = v
return str(dict(self.items()))
if __name__ == '__main__':
dic= {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh,en-US;q=0.9,en;q=0.8,zh-CN;q=0.7,zh-TW;q=0.6",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"user-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
}
dic1 = CaseInsensitiveDict(dic)
print(dic1.get("UseR-agEnt"))
python 字典不区分大小写工具类的更多相关文章
- Python基础之自定义工具类
class ListHelper: @staticmethod def find_all(target, func_condition): """ 查找列表中满足条件的所 ...
- python字典不区分大小写
from multidict import CIMultiDict dic=CIMultiDict() dic["key"]="1234" print(dic[ ...
- Java调用Python脚本工具类
[本文出自天外归云的博客园] 在网上查了很多方法都不成功,在google上搜到一篇文章,做了一些小修改,能够处理中文输出.提取一个运行python脚本的Java工具类如下: package com.a ...
- Go/Python/Erlang编程语言对比分析及示例 基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!
Go/Python/Erlang编程语言对比分析及示例 本文主要是介绍Go,从语言对比分析的角度切入.之所以选择与Python.Erlang对比,是因为做为高级语言,它们语言特性上有较大的相似性, ...
- Python数据库工具类MySQLdb使用
MySQLdb模块用于连接mysql数据库. 基本操作 # -*- coding: utf-8 -*- #mysqldb import time, MySQLdb ...
- 一个python爬虫工具类
写了一个爬虫工具类. # -*- coding: utf-8 -*- # @Time : 2018/8/7 16:29 # @Author : cxa # @File : utils.py # @So ...
- Python中xml、字典、json、类四种数据的转换
最近学python,觉得python很强很大很强大,写一个学习随笔,当作留念注:xml.字典.json.类四种数据的转换,从左到右依次转换,即xml要转换为类时,先将xml转换为字典,再将字典转换为j ...
- Python工具类(二)—— 操作时间相关
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = '操作时间的工具类' "" ...
- Python工具类(一)—— 操作Mysql数据库
如何调用直接看__main__函数里如何调用此工具类就阔以啦! # encoding=utf-8 import pymysql # 导入所有Mysql配置常量,请自行指定文件 from conf.se ...
随机推荐
- script ajax / XHR / XMLHttpRequest
s 利用XHR 调试发送form data表单数据,F5键刷新form表单URL ,http请求地址,获取token,提交. 如:http://pcp.cns*****.com/spcp-web/vm ...
- 解决ubuntu中arm-linux-gcc not found
1. 注意检查是不是 换了bash的原因 2. 此外还有权限切换以后环境变量换了 3.如果遇到环境变量配置以后,能够找到版本(也就是说 输入 命令的开头按tab以后能够出现补全),这是因为64位下运行 ...
- redis安全问题【原】
前提 假设redis安装在 IP 地址为 192.168.0.123 的linux服务器 . 我的本机Win10操作系统 IP地址为 192.168.0.45 , 有一套java客户端代码可调用lin ...
- 1.关于Java
一.Java简介 1.java语言的特性 java语言的重要特性:跨平台: 一次编译,到处运行. 2.java的环境搭建: 1.JRE: java运行环境. JRE = java 虚拟机 + 核心类库 ...
- Chimee - 简单易用的H5视频播放器解决方案
Chimee是由奇舞团开源的一套H5视频播放器解决方案,由奇舞团视频云前端团队结合在业务和视频编解码方向的沉淀积累倾心打造.Chimee支持MP4.M3U8.FLV等多种媒体格式,同时它也帮我们解决了 ...
- webpack-config.js 内容讲解
当我们需要和后台分离部署的时候,必须配置config/index.js: 用vue-cli 自动构建的目录里面 (环境变量及其基本变量的配置) var path = require('path') m ...
- jQuery two way bindings(双向数据绑定插件)
jQuery two way bindings https://github.com/petersirka/jquery.bindings 这是一个简单的jQuery双向绑定库. 此插件将HTML元素 ...
- 关于hashMap中 计算hashCode的逻辑推理(二)
hashMap中,为了使元素在数组中尽量均匀的分布,所以使用取模的算法来决定元素的位置.如下: //方法一: static final int hash(Object key){//jdk1.8 in ...
- APPLE-SA-2019-3-25-7 Xcode 10.2
APPLE-SA-2019-3-25-7 Xcode 10.2 Xcode 10.2 is now available and addresses the following: KernelAvail ...
- Cisco Common Service Platform Collector - Hardcoded Credentials(CVE-2019-1723)
Cisco Common Service Platform Collector - Hardcoded Credentials 思科公共服务平台收集器-硬编码凭证(CVE-2019-1723) htt ...