iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python dict
  • 217
分享到

python dict

pythondict 2023-01-31 03:01:48 217人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

1、Dictionary语法 Dictionary由key/value对(称为项目)组成,key和value之间用“:”分割,项目用“,”分割,所有项目用“{}”包括起来 >>> phonebook = {

1、Dictionary语法

  • Dictionary由key/value对(称为项目)组成,key和value之间用“:”分割,项目用“,”分割,所有项目用“{}”包括起来
>>> phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
  • Dictionary的key值必须唯一,否则后者会覆盖前者:
>>> phonebook = {'Alice': '2341', 'Alice': '9102', 'Cecil': '3258'}>>> phonebook{'Alice': '9102', 'Cecil': '3258'}
  • 使用dict()函数可以从Mapping(如其它的Dictionary)或key/value形式的Sequence创建Dictionary:
>>> items = [('name', 'Gumby'), ('age', 42)]>>> d = dict(items)>>> d{'age': 42, 'name': 'Gumby'}
  • 也可以用keyWord参数来创建Dictionary:
>>> d = dict(name='Gumby', age=42)>>> d{'age': 42, 'name': 'Gumby'}
2、基本Dictionary操作
  • Dictionary支持Sequence的基本操作,但要注意下面几点:
  • key值可以是任何类型,但必须是不可变类型,如整数、浮点数、String、Tuple
  • 对项目赋值时,如果key值不存在,会新建项目:
>>> x = {}>>> x[42] = 'Foobar'>>> x{42: 'Foobar'}
  • 使用in操作符时,是查找key值,而不是value值

3、使用Dictionary格式化String

  • 转换形式:%(key)type(type是转换类型)
>>> template = '''<html><head><title>%(title)s</title></head><body><h1>%(title)s</h1><p>%(text)s</p></body>'''>>> data = {'title': 'My Home Page', 'text': 'Welcome to my home page!'}>>> print template % data<html><head><title>My Home Page</title></head><body><h1>My Home Page</h1><p>Welcome to my home page!</p></body>
4、Dictionary方法

(1) clear:移去Dictionary中所有的元素

>>> d = {'age': 42, 'name': 'Gumby'}>>> d{'age': 42, 'name': 'Gumby'}>>> d.clear()>>> d{}
  • 注意,d.clear()和d = {}结果相同,但含义不同:后者是指向了一个新的空Dictionary

(2) copy:返回具有相同key/value对的新Dictionary(注意value值是共用的)

>>> x = {'username': 'admin', 'Machines': ['foo', 'bar', 'baz']}>>> y = x.copy()>>> y['username'] = 'mlh'>>> y['machines'].remove('bar')>>> y{'username': 'mlh', 'machines': ['foo', 'baz']}>>> x{'username': 'admin', 'machines': ['foo', 'baz']}
  • 避免上面问题的方法是对value值也进行拷贝,可以使用copy模块中的deepcopy()函数:
>>> from copy import deepcopy>>> d = {}>>> d['names'] = ['Alfred', 'Bertrand']>>> c = d.copy()>>> dc = deepcopy(d)>>> d['names'].append('Clive')>>> c{'names': ['Alfred', 'Bertrand', 'Clive']}>>> dc{'names': ['Alfred', 'Bertrand']}


(3) fromkeys:根据给定的key值创建新的Dictionary,缺省value值为None

>>> {}.fromkeys(['name', 'age']){'age': None, 'name': None}
  • 可以使用Dictionary的Type(后面讲述):dict
>>> dict.fromkeys(['name', 'age']){'age': None, 'name': None}
  • 可以指定value的缺省值:
>>> dict.fromkeys(['name', 'age'], '(unknown)'){'age': '(unknown)', 'name': '(unknown)'}

(4) get:获取项目的value值(不常用)

  • 注意下面的区别:
>>> d = {}>>> print d['name']Traceback (most recent call last): File "<interactive input>", line 1, in ?KeyError: 'name'>>> print d.get('name')None
  • 可以指定缺省值(缺省是None):
>>> d.get('name', 'N/A')'N/A'

(5) has_key:检查Dictionary中是否有指定key

>>> d = {}>>> d.has_key('name')0>>> d['name'] = 'Eric'>>> d.has_key('name')1

(6) items和iteritems

  • items()以List返回Dictionary中所有项目,每个项目的形式是(key, value):
>>> d = {'title': 'python WEB Site', 'url': 'Http://www.Python.org', 'spam': 0}>>> d.items()[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]
  • iteritems()返回Iterator对象:
>>> d.iteritems()<dictionary-itemiterator object at 0x0101CA60>>>> list(d.iteritems())[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]

(7) keys和iterkeys

>>> d.keys()['url', 'spam', 'title']>>> d.iterkeys()<dictionary-keyiterator object at 0x01073720>>>> list(d.iterkeys())['url', 'spam', 'title']

(8) pop:根据指定key返回value,并从Dictionary中移去该项目:

>>> d = {'x': 1, 'y': 2}>>> d.pop('x')1>>> d{'y': 2}

(9) popitem:从Dictionary中随机弹出一个项目返回(Dictionary中的项目是无序的)

>>> d = {'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}>>> d.popitem()('url', 'http://www.python.org')>>> d{'spam': 0, 'title': 'Python Web Site'}

(10) setdefault:根据指定的key值,对不在Dictionary的项目设置value值

>>> d = {}>>> d.setdefault('name', 'N/A')'N/A'>>> d{'name': 'N/A'}>>> d['name'] = 'Gumby'>>> d.setdefault('name', 'N/A')'Gumby'>>> d{'name': 'Gumby'}
  • 如果不指定缺省值,则使用None

(11) update:使用另一个Dictionary的项目来更新指定Dictionary

>>> d = {'title': 'Python Web Site', 'url': 'http://www.python.org', 'changed': 'Mar 14 22:09:15 MET 2005'}>>> x = {'title': 'Python Language Website'}>>> d.update(x)>>> d{'url': 'http://www.python.org', 'changed': 'Mar 14 22:09:15 MET 2005', 'title': 'Python Language Website'}(12) values和itervalues>>> d.values()['http://www.python.org', 'Mar 14 22:09:15 MET 2005', 'Python Language Website']>>> d.itervalues()<dictionary-valueiterator object at 0x01073900>>>> list(d.itervalues())

--结束END--

本文标题: python dict

本文链接: https://www.lsjlt.com/news/187626.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python dict
    1、Dictionary语法 Dictionary由key/value对(称为项目)组成,key和value之间用“:”分割,项目用“,”分割,所有项目用“{}”包括起来 >>> phonebook = {...
    99+
    2023-01-31
    python dict
  • Python -- dict 类
    Python dict类常用方法:class dict(object):        def clear(self):  #清除字典中所有元素形成空字典,del是删除整个字典; >>> test {'k2': 'v2',...
    99+
    2023-01-31
    Python dict
  • python dict sorted 排
    python dict sorted 排序 转载自http://hi.baidu.com/jackleehit/blog/item/53da32a72207bafa9052eea1.html 我们知道Python的内置dictionary...
    99+
    2023-01-31
    python dict sorted
  • python 字典dict
    # -*- coding: utf-8 -*- # ****************************** 创建 *************************** dict1 = {} #定义1个元素的字典 dict2 = ...
    99+
    2023-01-31
    字典 python dict
  • python字典 dict
    #dict 字典;是一种key:value的数据类型,没有下标,是无序的。字典可以嵌套任何类型,可以嵌套很多层。 #格式 dict1 = {     "name1":"123",     "name2":"456",     "name4"...
    99+
    2023-01-31
    字典 python dict
  • python之dict与set
    dict全称dictionary,使用键-值(key-value)存储,书写一个dictname={:::} (name[])当数据量大时,字典比列表和元组速度快dict实现原理和查字典是一样的,假设字典包含一万字,list查询方法是一个一...
    99+
    2023-01-31
    python dict set
  • Python-Dict&Set类型
    Python的另外两种重要的数据类型Dict和Set,可以快速按照关键字检索信息 Dict - 字典 list 和 tuple 可以用来表示顺序集合,例如,班里同学的名字: ['Adam', 'Lisa', 'Bart'] 或者考试的...
    99+
    2023-01-31
    类型 Python Dict
  • Python Dict用法
    #字典的添加、删除、修改操作dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}dict["w"] = "watermelon"del(dict["a"]...
    99+
    2023-01-31
    Python Dict
  • Python字典dict
    dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。Python中的唯一一种映射类型。 举个例子,假设要根据同学的名字...
    99+
    2023-01-31
    字典 Python dict
  • Python中的dict
    # dict # Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 d = {'Michael': 95, 'Bob': 75,...
    99+
    2023-01-31
    Python dict
  • Python中字典dict
    字典是一种组合数据,没有顺序的组合数据,数据以键值对形式出现 # 字典的创建 # 创建空字典1 d = {} print(d) # 创建空字典2 d = dict() print(d) # 创建有值的字典, 每一组数据用冒号隔...
    99+
    2023-01-30
    字典 Python dict
  • python的dict,set,list
    字典(dict)dict 用 {} 包围 dict.keys(),dict.values(),dict.items() hash(obj)返回obj的哈希值,如果返回表示可以作为dict的key del 或 dict.pop可以删除一个it...
    99+
    2023-01-31
    dict python list
  • python xml转成dict
    可以转成dict   defdictlist(node):     res={}     res[node.tag]={}     xmltodict(node,res[node.tag])    ...
    99+
    2023-01-31
    转成 python xml
  • 详解Python中的Dict
    目录什么是dict?我们下面看看dict的增删查改总结什么是dict? dict全称为dictionary(字典),人如其名,像字典一样可以根据索引定位到特定的文字。 在python...
    99+
    2024-04-02
  • Python对Dict排序
    对下面的Dict: aps = {} for key in T.keys(): ap = average_precision(T[key], P[key]) aps[key] = ap ...
    99+
    2023-01-31
    Python Dict
  • python dict的list排序
    对于简单的list排序,直接调用内建函数就可以了,但是对于dict的list排序就没有那么直接了,不过,还是有很简洁的办法的,如: >>> ls1 = [{'a' : 1, 'b' : 12}, {'a' : -1, '...
    99+
    2023-01-31
    python dict list
  • python dict 取值方法
      在日常工作中,我们经常会遇到需要将一些数据转换为 dict格式的情况。比如: 1、想要将多个数组按照某种规则进行排列,形成有序的数据表,这时需要使用 dict函数。 3、想要将数据按照指定的方式进行存储,比如:按行存储、按列存储等,这...
    99+
    2023-09-10
    python 算法 开发语言
  • python dict 与list比较
    Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度通过help(dict)可以查找dict有关的函数操作例如: dt  = dict(...
    99+
    2023-01-31
    python dict list
  • Python中的Set与dict
    目录一、Set集合类型二、set和dict的数据类型限制一、Set 集合类型 Set 集合类型 (交差并补) 特点 :无序 , 自动去重 集合用{}表示,元素间用逗号分隔建立集合类型...
    99+
    2024-04-02
  • Python基础——字典(dict)
    由键-值对构建的集合。 创建   dic1={} type(dic1)   dic2=dict() type(dic2)   初始化 dic2={'hello':123,'world':456,'python':789} ...
    99+
    2023-01-30
    字典 基础 Python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作