Python组合数据类型——映射类型:字典

简介: 字典:Python内置的数据结构之一,与列表一样是一个可变序列,以键值对的方式存储数据,字典是一个无序的序列。

1、字典类型

1.1什么是字典

字典: Python内置的数据结构之一,与列表一样是一个 可变序列,以 键值对的方式存储数据,字典是一个 无序的序列Python语言中的字典使用大括号 { }建立,每个元素是一个键值对。

键值对”是组织数据的一种重要方式,广泛应用在当代大型信息系统中,如Web系统。键值对的基本思想是将“值”信息关联一个“键”信息,进而通过键信息找对应的值信息,这个过程叫映射。Python语言中通过字典类型实现映射。

1.2字典示意图

在这里插入图片描述

1.3字典的原理

字典的原理: Python中的字典是根据 key查找 value所在的位置

1.4创建字典的方式

python中创建一个字典对象,常用的方式有两种。

  1. 第一种方式,使用花括号{ }
'''
第一种方式,使用花括号{},语法如下所示
使用{}创建字典
scores = {'张三': 100, '李四': 98, '王五': 45}
'''
scores = {'张三': 29, '李四': 10, '王五': 40}
print(scores)  # {'张三': 29, '李四': 10, '王五': 40}
print(type(scores))  # <class 'dict'>
  1. 第二种方式,使用内置函数dict()
'''第二种方式,使用内置函数dict()。dict即dictionary(字典)的缩写,语法如下所示。
字典名 = dict(键1=值1, 键2=值2)
'''
dic = dict(name='张三', age=20)
print(dic)  # {'name': '张三', 'age': 20}
  1. 创建空字典
d = {}
print(d)  # {}

1.5字典元素的获取

根据键key获取字典的值value

# 1.使用 [] 获取
scores = {'张三': 29, '李四': 10, '王五': 40}
print('张三' in scores)  # True
print('张三' not in scores)  # False
print(scores['张三'])  # 29
 
# 2.使用 get()方法
print(scores.get('张三'))  # 29
print(scores.get('柽柳'))   # None
print(scores.get('麻子', 99))  # 99是在查找 麻子值的(value)不存在时的一个默认值

2、字典类型的操作

2.1字典的操作函数

Python内置数据结构:字典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 key is not found, d is returned if given, otherwise KeyError is raised
        """
        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 __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 __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 __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 __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

字典类型的一些通用操作函数

操作函数 描述
dict() 生成一个字典
len(d) 字典d元素的个数(长度)
min(d) 字典d中键的最最小值
max(d) 字典d中键的最最大值

2.2字典的操作方法

字典类型有一些操作方法,使用的语法格式为:
<字典对象名>.<方法名>(<方法参数>)

操作方法 描述
d.keys() 返回字典d所有键的信息
d.values() 返回字典d所有值的信息
d.items() 返回字典d所有键值对
d.get(key, default) 键存在则返回相应值,否则返回默认值default
d.pop(key, default) 键存在则返回相应值,同时删除键值对,否则返回默认值default
d.popitem() 随机从字典中取出一个兼职对,以元组(key, value)的形式返回,同时将该键值对从字典中删除。
d.clear() 删除所有的键值对,清空字典

2.3字典元素的增删改操作

scores = {'张三': 29, '李四': 10, '王五': 40}

  • key的判断
# key的判断
scores = {'张三': 29, '李四': 10, '王五': 40}
print('张三' in scores)  # True
print('张三' not in scores)  # True
  • 字典的删除
# 字典元素的删除
del scores['张三']  # 删除指定的键值对
print(scores)  # {'李四': 10, '王五': 40}
  • 字典的清除
# 清空字典 clear()方法
scores.clear()
print(scores)  # {}
  • 字典元素的新增
# 新增元素
scores['陈六'] = 20
print(scores)  # {'陈六': 20}
  • 字典元素值的修改
# 修改value
scores['陈六'] = 100
print(scores)  # {'陈六': 100}

2.4字典视图的获取

  • 获取所有的键, <字典对象名>.keys()方法 返回值为列表
# 获取所有的键 .keys()方法 返回值为列表
scores = {'张三': 29, '李四': 10, '王五': 40}
print(scores.keys())  # dict_keys(['张三', '李四', '王五'])
print(type(scores.keys()))  # <class 'dict_keys'>
print(list(scores.keys()))  # ['张三', '李四', '王五']
  • 获取所有的值,<字典对象名>.value()方法,返回值为列表
# 获取所有的值 <字典对象名>.value()方法 返回值为列表
dict_values = scores.values()
print(dict_values)  # dict_values([29, 10, 40])
print(type(dict_values))  # <class 'dict_values'>
print(list(dict_values))  # [29, 10, 40]
  • 获取所有的键值对,<字典对象名>.items()方法 返回值为元组
#  获取所有的键值对  返回值为元组
print(scores.items())
# dict_items([('张三', 29), ('李四', 10), ('王五', 40)])

2.5字典元素的遍历

字典元素的遍历:使用for-in循环

# 字典元素的遍历
scores = {'张三': 29, '李四': 10, '王五': 40}
for item in scores:
    print(item, scores[item])

在这里插入图片描述

3、字典的特点

1.键 key 不可以重复,值 value可以重复

2.字典中元素是无序的

3.字典会浪费大的内存,是一种使用空间换时间的数据结构,但是查询速度快。

4、字典生成式

  • 内置函数zip()
用于将可迭代对象作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元组组成的列表
  • 字典生成式:
    {key: value for key, value in zip(items,prices)}
items = ['Fruits', 'Books', 'Others']  # 键的列表
prices = [96, 78, 85]  # 值的列表
d = {items: prices for items, prices in zip(items, prices)}  # 两个列表生成一个字典
print(d)  # {'Fruits': 96, 'Books': 78, 'Others': 85}

# .upper()方法 键字母变大写
d = {items.upper(): prices for items, prices in zip(items, prices)}  # 两个列表生成一个字典
print(d)  # {'Fruits': 96, 'Books': 78, 'Others': 85}


items = ['Fruits', 'Books', 'Others']  # 键的列表
prices = [96, 78, 85]  # 值的列表
a = dict(zip(items, prices))
print(a)  # {'Fruits': 96, 'Books': 78, 'Others': 85}

在这里插入图片描述

相关文章
|
9天前
|
存储 数据挖掘 程序员
揭秘Python:掌握这些基本语法和数据类型,你将拥有编程世界的钥匙!
【9月更文挑战第3天】Python 是一种简洁强大的高级编程语言,其清晰的语法和丰富的功能深受程序员喜爱。本文从基本语法入手,介绍 Python 的代码结构特点,如通过缩进区分代码块,使逻辑更清晰。接着详细讲解主要数据类型:数值型、字符串、列表、元组、集合与字典,每个类型均附有示例代码,帮助初学者快速掌握 Python,为后续学习打下坚实基础。
23 2
|
13天前
|
索引 Python
Python 中常见的内置数据类型
【8月更文挑战第29天】
15 3
|
13天前
|
索引 Python 容器
为什么Python中会有集合set类型?
为什么Python中会有集合set类型?
|
14天前
|
Python
Python变量的作用域_参数类型_传递过程内存分析
理解Python中的变量作用域、参数类型和参数传递过程,对于编写高效和健壮的代码至关重要。正确的应用这些概念,有助于避免程序中的错误和内存泄漏。通过实践和经验积累,可以更好地理解Python的内存模型,并编写出更优质的代码。
10 2
|
15天前
|
存储 Python 容器
python字典的常用操作方法
python字典的常用操作方法
|
15天前
|
存储 JSON JavaScript
使用 Python 将字典转换为 JSON
【8月更文挑战第27天】
14 2
|
20天前
|
存储 测试技术 数据格式
Python接口自动化测试框架(练习篇)-- 数据类型及控制流程(二)
本文通过数据类型转换和文件读取的练习,复习了Python中的数据类型、循环、条件判断、内置函数等基础知识,并演示了如何将字符串数据转换为字典列表,以及如何从文本文件中读取和转换数据。
30 1
|
13天前
|
Python
|
13天前
|
存储 数据库 Python
Python 中的字典是什么?
【8月更文挑战第29天】
13 0
|
14天前
|
Python
python在列表、元素、字典、集合和numpy的数组前加上星号 * 是什么含义,以及*args和**kwargs的使用
python在列表、元素、字典、集合和numpy的数组前加上星号 * 是什么含义,以及*args和**kwargs的使用
22 0