首页 > 编程语言 >Python 字典

Python 字典

时间:2023-06-09 18:47:21浏览次数:52  
标签:__ real Python self signature pass def 字典

Dict 数据类型

一、创建一个字典

>>> a = {'name': 'gm', 'age': 18}
>>> a
{'age': 18, 'name': 'gm'}

二、查看字典

# 获取字典a的值
>>> a
{'age': 18, 'name': 'gm'}

# 获取特定key的值
>>> a.['name']'gm'
>>> a.['age']18

三、查看列表可进行的操作

>>> dir(a)
['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
dict 函数方法
class dict(object):
    """
    dict() -> new empty dictionary
    dict(mapping) -> new dictionary initialized from a mapping object's
        (key, value) pairs
    dict(iterable) -> new dictionary initialized as if via:
        d = {}
        for k, v in iterable:
            d[k] = v
    dict(**kwargs) -> new dictionary initialized with the name=value pairs
        in the keyword argument list.  For example:  dict(one=1, two=2)
    """
    def clear(self): # real signature unknown; restored from __doc__
        """ D.clear() -> None.  Remove all items from D. """
        pass

    def copy(self): # real signature unknown; restored from __doc__
        """ D.copy() -> a shallow copy of D """
        pass

    @staticmethod # known case
    def fromkeys(*args, **kwargs): # real signature unknown
        """ Create a new dictionary with keys from iterable and values set to value. """
        pass

    def get(self, *args, **kwargs): # real signature unknown
        """ Return the value for key if key is in the dictionary, else default. """
        pass

    def items(self): # real signature unknown; restored from __doc__
        """ D.items() -> a set-like object providing a view on D's items """
        pass

    def keys(self): # real signature unknown; restored from __doc__
        """ D.keys() -> a set-like object providing a view on D's keys """
        pass

    def pop(self, k, d=None): # real signature unknown; restored from __doc__
        """
        D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
        
        If the key is not found, return the default if given; otherwise,
        raise a KeyError.
        """
        pass

    def popitem(self, *args, **kwargs): # real signature unknown
        """
        Remove and return a (key, value) pair as a 2-tuple.
        
        Pairs are returned in LIFO (last-in, first-out) order.
        Raises KeyError if the dict is empty.
        """
        pass

    def setdefault(self, *args, **kwargs): # real signature unknown
        """
        Insert key with a value of default if key is not in the dictionary.
        
        Return the value for key if key is in the dictionary, else default.
        """
        pass

    def update(self, E=None, **F): # known special case of dict.update
        """
        D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
        If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
        If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
        In either case, this is followed by: for k in F:  D[k] = F[k]
        """
        pass

    def values(self): # real signature unknown; restored from __doc__
        """ D.values() -> an object providing a view on D's values """
        pass

    def __class_getitem__(self, *args, **kwargs): # real signature unknown
        """ See PEP 585 """
        pass

    def __contains__(self, *args, **kwargs): # real signature unknown
        """ True if the dictionary has the specified key, else False. """
        pass

    def __delitem__(self, *args, **kwargs): # real signature unknown
        """ Delete self[key]. """
        pass

    def __eq__(self, *args, **kwargs): # real signature unknown
        """ Return self==value. """
        pass

    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __ge__(self, *args, **kwargs): # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs): # real signature unknown
        """ Return self>value. """
        pass

    def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
        """
        dict() -> new empty dictionary
        dict(mapping) -> new dictionary initialized from a mapping object's
            (key, value) pairs
        dict(iterable) -> new dictionary initialized as if via:
            d = {}
            for k, v in iterable:
                d[k] = v
        dict(**kwargs) -> new dictionary initialized with the name=value pairs
            in the keyword argument list.  For example:  dict(one=1, two=2)
        # (copied from class doc)
        """
        pass

    def __ior__(self, *args, **kwargs): # real signature unknown
        """ Return self|=value. """
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    def __len__(self, *args, **kwargs): # real signature unknown
        """ Return len(self). """
        pass

    def __le__(self, *args, **kwargs): # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs): # real signature unknown
        """ Return self<value. """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __ne__(self, *args, **kwargs): # real signature unknown
        """ Return self!=value. """
        pass

    def __or__(self, *args, **kwargs): # real signature unknown
        """ Return self|value. """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    def __reversed__(self, *args, **kwargs): # real signature unknown
        """ Return a reverse iterator over the dict keys. """
        pass

    def __ror__(self, *args, **kwargs): # real signature unknown
        """ Return value|self. """
        pass

    def __setitem__(self, *args, **kwargs): # real signature unknown
        """ Set self[key] to value. """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ D.__sizeof__() -> size of D in memory, in bytes """
        pass

    __hash__ = None

四、常用的字典操作

  • 插入新的键值
# 插入新的键值
>>> a
{'age': 18, 'name': 'gm'}
>>> a['job'] = '运维'
>>> a
{'age': 18, 'job': '运维', 'name': 'gm'}
  • 修改字典某键的值
# 修改字典某键的值
>>> a
{'age': 18, 'name': 'gm'}
>>> a['name']='root'
>>> a
{'age': 18, 'name': 'root'}
  • 获取字典某元素的值
# 获取字典某元素的值
>>> a
{'age': 18, 'job': '运维', 'name': 'gm'}
>>> a['gender']
Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    a['gender']
KeyError: 'gender'

>>> a.get('gender')
>>> a.get('gender',-1)
-1
>>> a.get('name',-1)
'gm'
  • 删除字典某元素
# 删除字典某元素
>>> a
{'age': 18, 'job': '运维', 'name': 'gm'}
>>> a.pop('job')
'运维'
>>> a
{'age': 18, 'name': 'gm'}

# 获取字典删除的元素的值
>>> a
{'age': 18, 'job': '运维', 'name': 'gm'}
>>> c = a.pop('job')
>>> c
'运维'
>>> a
{'age': 18, 'name': 'gm'}
  • keys()、values()、items()方法
# Python3中字典的keys()、values()、items()方法的区别
>>> a.keys()       # 以列表返回字典所有的键
dict_keys(['age', 'job', 'name'])

>>> a.values()     # 以列表返回字典中的所有值
dict_values([18, '运维', 'gm'])

>>> a.items()      # 以列表返回字典可遍历的(键, 值) 元组数组
dict_items([('age', 18), ('job', '运维'), ('name', 'gm')])

五、字典练习

有如下值集合 [11,22,33,44,55,66,77,88,99,90...],
将所有大于 66 的值保存至字典的第一个key中,
将小于 66 的值保存至第二个key的值中。
即: {'k1': 大于66 , 'k2': 小于66}
b = {}
a = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90, ]

for i in a:
    if i > 66:
        if 'k1' in b.keys():
            b['k1'].append(i)
        else:
            b['k1']= [i, ]
    else:
        if 'k2' in b.keys():
            b['k2'].append(i)
        else:
            b['k2']= [i, ]

print(b)
print(b['k1'])
print(b['k2'])
  • 运行结果
{'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]}

[77, 88, 99, 90]
[11, 22, 33, 44, 55, 66]

标签:__,real,Python,self,signature,pass,def,字典
From: https://www.cnblogs.com/evescn/p/17470005.html

相关文章

  • python3中print()函数打印多个变量值
    第一种方法:print("变量1",file_name,"变量2",new_name) print("变量1",file_name,"变量2",new_name) 第二种方法:print("变量1:%s变量2:%s"%(file_name,new_name)) print("变量1:%s变量2:%s"%(file_name,new_nam......
  • python装饰器
    '''1将outer定义代码块读入内存中,没有调用outer()2解释装饰器的作用2.1立即执行作为装饰器的函数outer(被装饰的函数名)2.2被装饰的函数名f1作为参数被传递给装饰函数outer(f1)3解释2装饰器的注意事项3.1装饰函数无论有无()都会执行3.2装饰函数里的参......
  • 实验六 实验6 turtle绘图与python库应用编程体验
    task1_1源代码:fromturtleimport*defmove(x,y):'''画笔移动到坐标(x,y)处'''penup()goto(x,y)pendown()defdraw(n,size=100):'''绘制边长为size的正n变形'''foriinrange(n):......
  • Python 元组
    Tuple数据类型一、如何创建元组>>>t=(1,2,3,'root')>>>t(1,2,3,'root')二、元组和列表的区别list是一种有序的集合,可以随时添加和删除其中的元素。元组也是一种有序列表,和list非常类似,不同点是tuple一旦定义了就不可修改,在一定意义上这也提高了代码的安全性......
  • python-类作为装饰器的各种情况
    1.装饰器没有参数:这时foo不再是之前的函数名而是类ClassDeco的一个对象,并且foo.func=foo,对象名()会触发类ClassDeco的__call__方法:classClassDeco:def__init__(self,func):self.func=funcdef__call__(self,*args,**kwargs):print(f'Runni......
  • Python 用户登录程序
    用户登录程序任务内容1、输入用户名和密码2、认证成功后显示欢迎信息3、输错3次后锁定流程图代码1、主文件importsyslock="lock.txt"logfile="login.txt"login_info=0i=0whilei<3andlogin_info==0:name=input("Pleaseinputyourname......
  • python selenium 模拟实现滑块验证码
    canndy_test.pyimportcv2importnumpyasnpdefmatchImg(imgPath1,imgPath2):imgs=[]#原始图像,用于展示sou_img1=cv2.imread(imgPath1)sou_img2=cv2.imread(imgPath2)#原始图像,灰度#最小阈值100,最大阈值500img1=cv2......
  • Python程序与设计
    2-27在命令行窗口中启动的Python解释器中实现在Python自带的IDLE中实现print("Helloworld")编码规范每个import语句只导入一个模块,尽量避免一次导入多个模块不要在行尾添加分号“:”,也不要用分号将两条命令放在同一行建议每行不超过80个字符使用必要的空行可以增加代码的可读性运算......
  • python3-类的专有方法
    1、介绍专有方法,具有私有方法的特性,即只能在类中被调用,是编程语言所准备的特殊作用的方法。2、方法说明2.1__init__构造方法,在对象创建时被调用。可以在方法中声明对象属性,以及其它初始化操作2.2__del__删除方法,当对象被释放时调用,可以在其中写一些对象结束时操作的代码......
  • python010 控制多台同类型设备
    defauto_find():rm=pyvisa.ResourceManager()devices=rm.list_resources()print(devices)ins_dict={'p1':None,'p2':None,'m1':None,'m2':None}counts={'p1':0,'p2'......