Python字典部分源码分析,字典是无序的

1 def clear(self): # real signature unknown; restored from __doc__
2         """ D.clear() -> None.  Remove all items from D. """
3         pass
1 #练习1、清空字典(置空)
2 li = {"key1":"value1","key2":"value2"}
3 li.clear()     #清空所有
4 print(li)
5 #执行结果:
6 {}
1 def copy(self): # real signature unknown; restored from __doc__
2         """ D.copy() -> a shallow copy of D """
3         pass
1 #练习2、浅拷贝
2 li = {"key1":"value1","key2":"value2","key3":"value3"}
3 dd = li.copy()    #浅拷贝
4 print(li)
5 print(dd)
6 #执行结果:
7 {‘key2‘: ‘value2‘, ‘key3‘: ‘value3‘, ‘key1‘: ‘value1‘}
8 {‘key2‘: ‘value2‘, ‘key3‘: ‘value3‘, ‘key1‘: ‘value1‘}
1  @staticmethod # known case
2     def fromkeys(*args, **kwargs): # real signature unknown
3         """ Returns a new dict with keys from iterable and values equal to value. """
4         pass
1 #练习3、迭代字符串生成同一值,放到新字典
2 li = {"key1":"value1","key2":"value2","key3":"value3"}
3 xin = li.fromkeys("key1","444")
4 print(xin)
5 aa = li.fromkeys("ttb","value1")  #分别迭代字符串生成同一个值,放在新字典中,与原字典好像没什么关系
6 print(aa)
7 #执行结果:
8 {‘1‘: ‘444‘, ‘y‘: ‘444‘, ‘e‘: ‘444‘, ‘k‘: ‘444‘}
9 {‘b‘: ‘value1‘, ‘t‘: ‘value1‘}
1 def get(self, k, d=None): # real signature unknown; restored from __doc__
2         """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
3         pass
1 #练习4、获取指定键的值
2 li = {"key1":"value1","key2":"value2","key3":"value3"}
3 aa = li.get("key2")    #获取指定键的值
4 print(aa)
5 #执行结果
6 value2
1 def items(self): # real signature unknown; restored from __doc__
2         """ D.items() -> a set-like object providing a view on D‘s items """
3         pass
1 #练习5、获取字典所有内容
2 li = {"key1":"value1","key2":"value2","key3":"value3"}
3 aa = li.items()    #获取字典所有
4 print(aa)
5 #执行结果:
6 dict_items([(‘key1‘, ‘value1‘), (‘key3‘, ‘value3‘), (‘key2‘, ‘value2‘)])
1 def keys(self): # real signature unknown; restored from __doc__
2         """ D.keys() -> a set-like object providing a view on D‘s keys """
3         pass
1 练习6、获取字典中所有键
2 li = {"key1":"value1","key2":"value2","key3":"value3"}
3 aa = li.keys()    #获取字典所有键
4 print(aa)
5 #执行结果:
6 dict_keys([‘key2‘, ‘key3‘, ‘key1‘])
1 def pop(self, k, d=None): # real signature unknown; restored from __doc__
2         """
3         D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
4         If key is not found, d is returned if given, otherwise KeyError is raised
5         """
6         pass
1 #练习7、删除指定键
2 li = {"key1":"value1","key2":"value2","key3":"value3"}
3 aa = li.pop("key2")    #删除指定键,连带删除值
4 print(li)
5 #执行结果
6 {‘key1‘: ‘value1‘, ‘key3‘: ‘value3‘}
1 def popitem(self): # real signature unknown; restored from __doc__
2         """
3         D.popitem() -> (k, v), remove and return some (key, value) pair as a
4         2-tuple; but raise KeyError if D is empty.
5         """
6         pass
1 #练习8、随机删除键值
2 li = {"key1":"value1","key2":"value2","key3":"value3"}
3 aa = li.popitem()    #随机删除指定键,连带删除值
4 print(li)
5 #执行结果:()随机删掉一个
6 {‘key3‘: ‘value3‘, ‘key1‘: ‘value1‘}
1 def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
2         """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
3         pass
 1 #练习9、输出指定键值,键不存在则加入字典
 2 li = {"key1": "value1", "key2": "value2", "key3": "value3"}
 3 aa = li.setdefault("key1","111")  # 键存在字典中时,相当于li.get("key1"),不管后面加什么都没影响
 4 print(aa)
 5 bb = li.setdefault("kkk","111")   #键不存在时,输入值,并且该键值会加入到字典中
 6 print(bb)
 7 print(li)
 8 执行结果:
 9 value1
10 111
11 {‘key2‘: ‘value2‘, ‘key1‘: ‘value1‘, ‘kkk‘: ‘111‘, ‘key3‘: ‘value3‘}
1 def update(self, E=None, **F): # known special case of dict.update
2         """
3         D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
4         If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
5         If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
6         In either case, this is followed by: for k in F:  D[k] = F[k]
7         """
8         pass
 1 #练习10、更新字典
 2 li = {"key1": "value1", "key2": "value2", "key3": "value3"}
 3 aa = {"key1":"111","key2":"222"}
 4 li.update(aa)      #aa是新的,把新的放进旧的,如果键相同则改变值,如果键不同则直接加入
 5 print(li)
 6 li1 = {"key1": "value1", "key2": "value2", "key3": "value3"}
 7 aa1 = {"key1":"111","key2":"222"}
 8 aa1.update(li1)
 9 print(aa1)
10 #执行结果:
11 {‘key3‘: ‘value3‘, ‘key1‘: ‘111‘, ‘key2‘: ‘222‘}
12 {‘key3‘: ‘value3‘, ‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘}
1 def values(self): # real signature unknown; restored from __doc__
2         """ D.values() -> an object providing a view on D‘s values """
3         pass
1 #练习11、输出字典所有值
2 li = {"key1": "value1", "key2": "value2", "key3": "value3"}
3 aa = li.values()    #输出字典所有的值
4 print(aa)
5 执行结果:
6 dict_values([‘value3‘, ‘value2‘, ‘value1‘])
时间: 2024-10-03 08:59:57

Python字典部分源码分析,字典是无序的的相关文章

K-近邻算法的Python实现 : 源码分析

网上介绍K-近邻算法的例子很多,其Python实现版本基本都是来自于机器学习的入门书籍<机器学习实战>,虽然K-近邻算法本身很简单,但很多初学者对其Python版本的源代码理解不够,所以本文将对其源代码进行分析. 什么是K-近邻算法? 简单的说,K-近邻算法采用不同特征值之间的距离方法进行分类.所以它是一个分类算法. 优点:无数据输入假定,对异常值不敏感 缺点:复杂度高 好了,直接先上代码,等会在分析:(这份代码来自<机器学习实战>) def classify0(inx, data

Python 进阶之源码分析:如何将一个类方法变为多个方法?

前一篇文章<Python 中如何实现参数化测试?>中,我提到了在 Python 中实现参数化测试的几个库,并留下一个问题: 它们是如何做到把一个方法变成多个方法,并且将每个方法与相应的参数绑定起来的呢? 我们再提炼一下,原问题等于是:在一个类中,如何使用装饰器把一个类方法变成多个类方法(或者产生类似的效果)? # 带有一个方法的测试类 class TestClass: def test_func(self): pass # 使用装饰器,生成多个类方法 class TestClass: def

python int的源码分析

在intobject.h中找到整数的定义 Python的整数对象的数据实际保存在ob_ival中,是c中的long类型.PyObject_HEAD就应该是整数对象的描述了.从源码的描述中知道PyObject_HEAD定义了整数对象的初始化信息 其中typedef struct _typeobject{}PyTypeObject,PyTypeObject可以被认为对象的最通用,最原始的类,被其他整数,字符串等对象继承使用. PyAPI_DATA(PyTypeObject)  PyInt_Type;

Python之namedtuple源码分析

namedtuple()函数根据提供的参数创建一个新类,这个类会有一个类名,一些字段名和一个可选的用于定义类行为的关键字,具体实现如下 namedtuple函数源码 from keyword import iskeyword as _iskeyword import sys as _sys import logging logging.basicConfig(level=logging.INFO, filename="logging.txt", filemode="w+&qu

python列表部分源码分析

1 def append(self, p_object): # real signature unknown; restored from __doc__ 2 """ L.append(object) -- append object to end """ 3 pass #1.练习(添加元素): li = [11,22,33,"aabc","cddg",234,"alex",] prin

Python编程_Selenium2Library源码分析

[Package] keywords 所有关键字封装 [Class] _waiting.py 等待函数的条件判断, 替换sleep, 在依次以条件逻辑执行较多用例时可以有效节省执行等待时间, 快速定位问题 _wait_until(self, timeout, error, function, *args) 概述: 直到function(*args)为True时return None, 为False则return error, 超时时间timeout 参数: error: 初始化为超时异常 fun

Python字典嵌套(源码分析/自定义)

今天在写监控脚本的时候遇到一个问题,就是我执行每一个监控模块(脚本)的时候,例如CPU.内存.磁盘脚本,都会返回一个字典格式的数据,但是我需要将这三个字典,组合成一个大字典,然后通过requests模块发送给api接口,so,我就在网上找了一些方法,然后总结,写成这编博文. 1.首先定义三个字典(不需要考虑字典的具体内容) >>> cpu_dict = {'cpu_count':8,'cpu_ratio':3.5} >>> memory_dict = {'memory_

redis源码分析3---结构体---字典

redis源码分析3---结构体---字典 字典,简单来说就是一种用于保存键值对的抽象数据结构: 注意,字典中每个键都是独一无二的:在redis中,内部的redis的数据库就是使用字典作为底层实现的: 1 字典的实现 在redis中,字典是使用哈希表作为底层实现的,一个hash表里面可以有多个hash表节点,而每个hash表节点就保存了字典中的一个键值对: hash表定义 table属性是一个数组,数组中的每个元素都是一个指向dictEntry结构的指针,每个dictEntry结构保存着一个键值

Python之美[从菜鸟到高手]--浅拷贝、深拷贝完全解读(copy源码分析)

可悲的我一直以为copy模块是用C写的,有时候需要深入了解deepcopy,文档描述的实在太简单,还是不知所云. 比如说最近看sqlmap源码中AttribDict的_deepcopy__有些疑惑, def __deepcopy__(self, memo): retVal = self.__class__() memo[id(self)] = retVal for attr in dir(self): if not attr.startswith('_'): value = getattr(se