iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python中的字典及举例
  • 709
分享到

Python中的字典及举例

字典Python 2023-01-31 02:01:53 709人浏览 八月长安

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

摘要

字典字典是python中的唯一的映射类型(哈希表)字典对象是可变的,但是字典的键必须使用不可变对象,一个字典中可以使用不同类型的键值。字典的方法    keys()    values()    items()举例如下:    In [10

字典

字典是python中的唯一的映射类型(哈希表)

字典对象是可变的,但是字典的键必须使用不可变对象,一个字典中可以使用不同类型的键值。

字典的方法

    keys()

    values()

    items()

举例如下:

    In [10]: dic = {}

    In [11]: type(dic)

    Out[11]: dict

    In [12]: dic = {'a':1,1:123}

    In [13]: dic

    Out[13]: {1: 123, 'a': 1}

    In [14]: dic = {'a':1,1:123,('a','b'):'hello'}

    In [15]: dic = {'a':1,1:123,('a','b'):'hello',[1]:1}

    ---------------------------------------------------------------------------

    TypeError                                 Traceback (most recent call last)

    <iPython-input-15-4fc52e86cb96> in <module>()

    ----> 1 dic = {'a':1,1:123,('a','b'):'hello',[1]:1}

    TypeError: unhashable type: 'list'

    In [16]: len(dic)

    Out[16]: 3

    In [17]: dic.keys()

    Out[17]: ['a', 1, ('a', 'b')]

    In [18]: dic.values()

    Out[18]: [1, 123, 'hello']

    In [19]: dic.get('a')

    Out[19]: 1

    In [20]: dic

    Out[20]: {1: 123, 'a': 1, ('a', 'b'): 'hello'}

    In [21]: dic[1]

    Out[21]: 123

更改字典内value:

    In [22]: dic['a'] = 2

    In [23]: dic

    Out[23]: {1: 123, 'a': 2, ('a', 'b'): 'hello'}

查看是不是在字典里

    In [28]: 'b' in dic

    Out[28]: False

    In [29]: 'a' in dic

    Out[29]: True

    In [30]: dic.has_key('a')

    Out[30]: True

    In [31]: dic.has_key('b')

    Out[31]: False

变为列表:

    In [32]: dic.items()

    Out[32]: [('a', 2), (1, 123), (('a', 'b'), 'hello')]

    In [33]: dic

    Out[33]: {1: 123, 'a': 2, ('a', 'b'): 'hello'}

复制字典:

    In [34]: dic1 = dic.copy()

    In [35]: dic1

    Out[35]: {1: 123, 'a': 2, ('a', 'b'): 'hello'}

    In [36]: dic

    Out[36]: {1: 123, 'a': 2, ('a', 'b'): 'hello'}

删除字典内容:

    In [37]: dic.pop(1)

    Out[37]: 123

    In [38]: dic

    Out[38]: {'a': 2, ('a', 'b'): 'hello'}

    In [39]: dic.pop(2)

    ---------------------------------------------------------------------------

    KeyError                                  Traceback (most recent call last)

    <ipython-input-39-9f97239cddce> in <module>()

    ----> 1 dic.pop(2)

    KeyError: 2

    In [40]:

更新字典,两个字典更新为一个:

    In [40]: dic1 = {1:1,2:2}

    In [41]: dic.update(dic1)

    In [42]: dic1

    Out[42]: {1: 1, 2: 2}

    In [43]: dic

    Out[43]: {1: 1, 2: 2, 'a': 2, ('a', 'b'): 'hello'}

创建字典:

    dic = {}

    dic = dict()

    help(dict)

    dict((['a',1],['b',2]))

    dict(a=1,b=2)

    fromkeys(),字典元素有相同的值时,默认为None.

    ddict = {}.fORMkeys(('x','y'),100)

    dic.fromkeys(range(100),100)

    In [45]: dic.fromkeys('abc')

    Out[45]: {'a': None, 'b': None, 'c': None}

    In [42]: dic = {}

    In [43]: dic

    Out[43]: {}

    In [44]: dict()

    Out[44]: {}

    In [45]: dict(x=10,y=100)

    Out[45]: {'x': 10, 'y': 100}

    In [46]: dict([('a',10),('b',20)])

    Out[46]: {'a': 10, 'b': 20}

访问字典:

    In [10]: dic={1:1,2:3,3:5}

    In [11]: dic

    Out[11]: {1: 1, 2: 3, 3: 5}

    In [12]: dic[2]

    Out[12]: 3

    In [13]: dic.items()

    Out[13]: [(1, 1), (2, 3), (3, 5)]

for循环访问:

    In [15]: for i in dic:

    ....:     print i,dic[i]

    ....:

    1 1

    2 3

    3 5

   

     In [18]: for i in dic:

    ....:     print "%s,%s" % (i,dic[i])

    ....:

    1,1

    2,3

    3,5

    In [19]: dic

    Out[19]: {1: 1, 2: 3, 3: 5}

    

    In [19]: dic

    Out[19]: {1: 1, 2: 3, 3: 5}

    In [21]: for k,v in dic.items():print k,v

    1 1

    2 3

    3 5

字典练习

    写出脚本,根据提示输入内容,并输入到字典中。

1种:

    [root@localhost python]# cat dict.py

    #!/usr/bin/python

    #Author is fengXiaQing

    #date 2017.12.22

    info = {}

    name = raw_input("Please input name:")

    age = raw_input("Please input age:")

    gender = raw_input("Please input (M/F):")

    info['name'] = name

    info['age'] = age

    info['gender'] = gender

    print info

    [root@localhost python]#

    [root@localhost python]# python dict.py

    Please input name:fxq

    Please input age:20

    Please input (M/F):M

    {'gender': 'M', 'age': '20', 'name': 'fxq'}

    [root@localhost python]#


2.种

    #!/usr/bin/python

    #Author is fengXiaQing

    #date 2017.12.22

    info = {}

    name = raw_input("Please input name:")

    age = raw_input("Please input age:")

    gender = raw_input("Please input (M/F):")

    info['name'] = name

    info['age'] = age

    info['gender'] = gender

    print info.items()

    [root@localhost python]# python dict.py

    Please input name:fxq

    Please input age:22

    Please input (M/F):M

    [('gender', 'M'), ('age', '22'), ('name', 'fxq')]

    [root@localhost python]#


3.种

    #!/usr/bin/python

    #Author is fengXiaQing

    #date 2017.12.22

    info = {}

    name = raw_input("Please input name:")

    age = raw_input("Please input age:")

    gender = raw_input("Please input (M/F):")

    info['name'] = name

    info['age'] = age

    info['gender'] = gender

    for i in info.items():

        print i

    print "main end"

    [root@localhost python]# python dict.py

    Please input name:fxq

    Please input age:22

    Please input (M/F):M

    ('gender', 'M')

    ('age', '22')

    ('name', 'fxq')

    main end

    [root@localhost python]#


4.种

    #!/usr/bin/python

    #Author is fengXiaQing

    #date 2017.12.22

    info = {}

    name = raw_input("Please input name:")

    age = raw_input("Please input age:")

    gender = raw_input("Please input (M/F):")

    info['name'] = name

    info['age'] = age

    info['gender'] = gender

    for k,v in info.items():

        print k,v

    print "main end"

    [root@localhost python]# python dict.py

    Please input name:fxq

    Please input age:22

    Please input (M/F):M

    gender M

    age 22

    name fxq

    main end

    [root@localhost python]#


5.种

    #!/usr/bin/python

    #Author is fengXiaQing

    #date 2017.12.22

    info = {}

    name = raw_input("Please input name:")

    age = raw_input("Please input age:")

    gender = raw_input("Please input (M/F):")

    info['name'] = name

    info['age'] = age

    info['gender'] = gender

    for k,v in info.items():

        print "%s:%s" % (k,v)

    print "main end"

    [root@localhost python]# python dict.py

    Please input name:fxq

    Please input age:22    

    Please input (M/F):M

    gender:M

    age:22

    name:fxq

    main end

    [root@localhost python]#


6.种

    #!/usr/bin/python

    #Author is fengXiaQing

    #date 2017.12.22

    info = {}

    name = raw_input("Please input name:")

    age = raw_input("Please input age:")

    gender = raw_input("Please input (M/F):")

    info['name'] = name

    info['age'] = age

    info['gender'] = gender

    for k,v in info.items():

        print "%s" % k

    print "main end"

    [root@localhost python]# python dict.py

    Please input name:fxq

    Please input age:22

    Please input (M/F):M

    gender

    age

    name

    main end

    [root@localhost python]#


练习:

    1. 现有一个字典dict1 保存的是小写字母a-z对应的ASCII码

    dict1 = {'a': 97, 'c': 99, 'b': 98, 'e': 101, 'd': 100, 'g': 103, 'f': 102, 'i': 105, 'h': 104, 'k': 107, 'j': 106, 'm': 109, 'l': 108, 'o': 96, 'n': 110, 'q': 113, 'p': 112, 's': 115, 'r': 114, 'u': 117, 't': 116, 'w': 119, 'v': 118, 'y': 121, 'x': 120, 'z': 122}

    1) 将该字典按照ASCII码的值排序

        print sorted(dict1.iteritems(), key=lambda d:d[1], reverse=False)

    2) 有一个字母的ASCII错了,修改为正确的值,并重新排序

        dict1['o']=111

        print sorted(dict1.iteritems(), key=lambda d:d[1], reverse=False)

    2. 用最简洁的代码,自己生成一个大写字母 A-Z 及其对应的ASCII码值的字典dict2(使用dict,zip,range方法)

        dict2 = dict(zip(string.uppercase,range(65,92)))

        print dict2

    3. 将dict2与第一题排序后的dict1合并成一个dict3

        dict3 = dict(dict1, **dict2)

        # dict3 = dict(dict1, **dict2)等同于下面的两行代码

        # dict3 = dict1.copy()

        # dict3.update(dict2)

        print dict3

        

--结束END--

本文标题: Python中的字典及举例

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

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

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

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

下载Word文档
猜你喜欢
  • Python中的字典及举例
    字典字典是python中的唯一的映射类型(哈希表)字典对象是可变的,但是字典的键必须使用不可变对象,一个字典中可以使用不同类型的键值。字典的方法    keys()    values()    items()举例如下:    In [10...
    99+
    2023-01-31
    字典 Python
  • Python中的字典及其应用
    一.字典创建1.赋值创建字典#赋值创建字典,key-value----键值对In [1]: d = {'key1': 'value', 'key2': 'value2'}In [2]: print d{'key2': 'value2', '...
    99+
    2023-01-31
    字典 及其应用 Python
  • python字典嵌套字典实例
    日志文件样式:2018-06-27 09:07:37 Postman[INFO]: [1530061656f8lda-7M5E9] from: <lilh@test.com><router>, to: <xie...
    99+
    2023-01-31
    字典 嵌套 实例
  • python中的字典及嵌套遍历
    目录python字典及嵌套遍历访问字典里的值修改字典删除字典元素嵌套字典遍历与内置函数字典的常用方法(定义、新增、删除、更新、遍历、嵌套等)什么是字典?为什么需要字典?字典总结pyt...
    99+
    2023-05-19
    python字典 python嵌套遍历 python遍历
  • Python中的循环退出举例及while
    循环退出 for循环:forelsefor 循环如果正常结束,都会执行else语句。脚本1:    #!/usr/bin/env python    for i in xrange(10):        print i    else: ...
    99+
    2023-01-31
    Python
  • python字典的小例子
    (helloworld) [root@iZ2ze7qh7q0di3qkvef1dzZ ~]# more dic_test.py#!/usr/bin/pythoninfo ={}name=raw_input("Please inpu...
    99+
    2023-06-02
  • Python 字典的使用详解及实例代码
    目录字典长什么样字典内能放什么访问字典内容修改字典内容删除字典数据字典内置函数字典是Python实现散列表数据结构的形式,表现映射的关系,一对一。 字典长什么样 {}这是一个空字典,...
    99+
    2024-04-02
  • Python中的字典及其使用方法
    目录一、使用字典1.访问字典中的值2.在字典中添加键值对3.修改字典中的值4.删除字典中的键值对5.由类似对象组成的字典二、遍历字典1.遍历字典中的所有键值对2.遍历字典中的所有键3...
    99+
    2024-04-02
  • python中的字典
    字典 :一个关联数组或散列表 ,可通过关键字索引的对象。字典的用途:定义一个可包含多个命名字段的对象,也可以用作快速查找无序数据的容器字典是python中最完善的数据类型 在程序中最常用于存储和处理数据如何创建:1,在{}中放入值即可创建一...
    99+
    2023-01-31
    字典 python
  • Python中关于字典的常规操作范例以及介绍
    目录1.字典的介绍2.访问字典的值(一)根据键访问值(二)通过get()方法访问值3.修改字典的值4.添加字典的元素(键值对)5.删除字典的元素6.字典常见操作1.len 测量字典中...
    99+
    2024-04-02
  • python(3)字典及列表
    列表list:打了激素的数组   数组是只能存储同一种数据类型的结构; 数组: scores[43] = [12, 12.0, "hello"] 元组tuple # 定义列表 li = [1, 1.0, "westos", (1,2,3,...
    99+
    2023-01-31
    字典 列表 python
  • 初学python案例 字典
    案例描述:    员工信息表存储在一个文件中,将信息表存储成字典,然后对字典进行模糊查询,查询到的数据进行高亮显示。例如输入  邹元武 ,输出匹配到的信息,并将其高亮显示员工信息表:001 黎伟晔 420822195711199638 男 ...
    99+
    2023-01-31
    字典 案例 python
  • Python中字典dict
    字典是一种组合数据,没有顺序的组合数据,数据以键值对形式出现 # 字典的创建 # 创建空字典1 d = {} print(d) # 创建空字典2 d = dict() print(d) # 创建有值的字典, 每一组数据用冒号隔...
    99+
    2023-01-30
    字典 Python dict
  • Python中字典的操作
    字典查找速度快 字典是无序的;(python3.6以上版本有序) 字典支持乘加、成员检查、长度、最小值、最大值、嵌套; 字典值不支持列表、元组、索引、切片、元素赋值跟切片赋值; 字典通过大括号表示; 字典的内容是项;项由键和值组成,中...
    99+
    2023-01-30
    字典 操作 Python
  • python中字典的练习
    源代码如下:#!/usr/bin/env python#Filename:addressbook.pyadbook={'alice':100,'bob':101,'chanel':102}while True:    choice=raw_...
    99+
    2023-01-31
    字典 python
  • Python 中的字典操作
    字典:dict 字典在其他编程语言中又称作关联数组或散列表 通过键实现元素存取: 无序集合,可变类型容器,长度可变,异构,嵌套 表示方法: phonebook = {'Alice':'1234','Beth':'9102',...} 字...
    99+
    2023-01-31
    字典 操作 Python
  • python字典添加值的方法及实例代码分享
    对于字典的操作,本篇介绍的是在其中添加值的方法,下面带来详细的介绍。 1、通过键=值的方式进行添加。如果键存在,则会将旧的值进行覆盖,如果不存在则添加。 addDic1 = { ...
    99+
    2022-11-21
    python 字典 添加值
  • python中字典的比较
    今天碰到一个字典比较的问题,就是比较两个字典的大小,其实这个用的不多,用处也没多少,但是还是记录一下。 字典的比较顺序如下: 1、先比较字典的元素的个数,那个多,就哪个大; 2、比较字典的键,在比较字典的键的时候,需要注意的是比较的顺序...
    99+
    2023-01-31
    字典 python
  • Python中字典的用法
    Python中字典的用法 注:以下所有示例使用的是Python3.5.版本 Python中的字典与C++中的map容器很相似,都是键值对的形式存储,然而Python中对字典的操作远比C++中对map的操作要方便的多。C++中的map与Py...
    99+
    2023-01-31
    字典 Python
  • Python的字典 { }
    Python的字典属于一种数据类型,我们可以把数据存到字典里面,字典使用大括号“{}”来定义。比如现在要存储一个人的信息然后读取出来,就可以使用切片的方式来体现: In [1]: info ='Tom 180 Male' In [2]: ...
    99+
    2023-01-31
    字典 Python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作