首页 > 编程语言 >python基础-字典常用操作

python基础-字典常用操作

时间:2022-10-19 22:03:28浏览次数:47  
标签:常用 name python age person dict key print 字典

1.通过key获取value

  dict = {key1: value1, key2:value2}

  dict['key1'] 可获取到key1对应的value1  

person = {'name': 'tt', 'age': 13}
print(person['age'])  # 13

test_dict = {'name': 'll', 'age': 90}
print(test_dict['height'])  # 无value时程序报错,KeyError: 'height'

  通过dict[key] = value ,当key值存在是,会修改原value、当key值不存在时,会将key:value键值对添加到字典中;

person = {'name': 'tt', 'age': 13}
person['age'] = 24
print(person)  # {'name': 'tt', 'age': 24}
person['height'] = 178
print(person)  # {'name': 'tt', 'age': 24, 'height': 178}

 

2.字典的update()方法

  dict.update(new_dict) 一次添加多个键值对,同样key值存在时更新key对应的value、key值不存在是添加key:value对;

person = {'name': 'tt', 'age': 13}
person.update({'like': 'football', 'age': 134})
print(person)  # {'name': 'tt', 'age': 134, 'like': 'football'}

 

3.字典的setdefault()方法

  dict.setdefault(key, default_value)  

  key值存在时,直接返回对应的value;key值不存在时,将key: default_value键值对添加进字典;

  default_value值可省略,默认是None;

person = {'name': 'tt', 'age': 13}
print(person.setdefault('age', 45))  # 13
print(person.setdefault('like', 'football'))  # football
print(person)  # {'name': 'tt', 'age': 13, 'like': 'football'}
print(person.setdefault('height'))  # None
print(person)  # {'name': 'tt', 'age': 13, 'like': 'football', 'height': None}

 

4.获取字典全部值

  dict.keys()  获取字典中全部key值,返回一个伪列表;

  dict.values() 获取字典中全部value的值,返回一个伪列表;

  dict.items() 获取字典所有的键值对, 返回伪列表,各键值对存在列表内的元组中;

person = {'name': 'tt', 'age': 13}
print(person.keys())  # dict_keys(['name', 'age'])
print(list(person.keys()))  # ['name', 'age'] (可以转化成列表)

print(person.values())  # dict_values(['tt', 13])
print(list(person.values()))  # ['tt', 13]

print(person.items())  # dict_items([('name', 'tt'), ('age', 13)])
print(list(person.items()))  # [('name', 'tt'), ('age', 13)]

 

5.字典的get() 方法

  dict.get(key)  获取对应value,无key时、默认返回None;

  dict.get(key,  default_value)  无key时,可以指定返回结果default_value;

person = {'name': 'tt', 'age': 13}
print(person.get('age'))  # 13
print(person.get('like'))  # None
print(person.get('like', 'no key'))  # no key

print(person['like'])  # 程序报错,KeyError: 'like'
# person['like']方式比get()方式可以节省部分时间,不用做key是否存在的判断(但基本可忽略不计)
# get()方式比person['like']方式,在返回结果上更友善些

 

6.字典的删除操作

  dict.pop(key)  删除key:value对,并返回value值;key不存在时会报错;

  dict.clear()  清空字典;

  dict.popitem()  删除字典的最后一个键值对, 返回键值对存储在元组中;

  同样可借助python内置函数del;

person = {'name': 'tt', 'age': 13, 'like': 'football', 'height': 168}
print(person.pop('name'))  # tt (操作有返回值,值是value)
print(person)  # {'age': 13, 'like': 'football', 'height': 168}

print(person.popitem())  # ('height', 168)
print(person)  # {'age': 13, 'like': 'football'}

del person['like']
print(person)  # {'age': 13}
# del person['name']  # KeyError: 'name' (无对应key时,会报错)

person.clear()
print(person)  # {}

 

7.字典的copy()函数

  复制字典内元素生成新字典;

# dict.copy() 依旧属于浅拷贝
person = {
    'xiaoming': {
        'age': 23,
        'height': 178
    },
    'xiaohong': {
        'age': 26,
        'height': 168
    }
}
new_person = person.copy()
new_person['xiaoming']['age'] = 999
print(new_person)  # {'xiaoming': {'age': 999, 'height': 178}, 'xiaohong': {'age': 26, 'height': 168}}
print(person)  # {'xiaoming': {'age': 999, 'height': 178}, 'xiaohong': {'age': 26, 'height': 168}}
# import copy, copy.deepcopy() 可完成深拷贝操作
import copy
person = {
    'xiaoming': {
        'age': 23,
        'height': 178
    },
    'xiaohong': {
        'age': 26,
        'height': 168
    }
}
new_person = copy.deepcopy(person)
new_person['xiaoming']['age'] = 999
print(new_person)  # {'xiaoming': {'age': 999, 'height': 178}, 'xiaohong': {'age': 26, 'height': 168}}
print(person)  # {'xiaoming': {'age': 23, 'height': 178}, 'xiaohong': {'age': 26, 'height': 168}}

 

8.其它简单操作

  in ,not in 成员判断;

  len(dict) 判断字典长度;

test_dict = {'name': 'll', 'age': 90}
print('name' in test_dict)  # True
print(len(test_dict))  # 2

# 字典没有累加累乘操作

  

总结

    

标签:常用,name,python,age,person,dict,key,print,字典
From: https://www.cnblogs.com/white-list/p/16807777.html

相关文章

  • Python - jsonpath 简单使用
    第三方包使用的时候需要单独安装使用场景:快速提取接口返回的JSON串中的某一个字段的值importjsonimportjsonpathjson_str='''{"success":tru......
  • python__list&tuple
    1classmates=['Michael','Bob','Tracy']2print(classmates)3print(len(classmates))4print(classmates[-1])5classmates.append("adma")6print(clas......
  • Go 开发常用操作技巧--字符串
    Go语言字符串的字节使用的是UTF-8编码,是一种变长的编码方式。使用1~4个字节表示一个符号,根据不同的符号而变化字节长度。含中文字符串截取字符串的长度我们可以使用l......
  • 常用内置模块
    包的使用#PS:虽然python3之后的版本中并不再要求包内必须含有__init__.py,但是考虑到兼容性问题,我们在创建包文件时,还是推荐加上__init__.py当我们再python中导入包时......
  • UE5 中用 Python 接口创建 Level Sequence 与设置 TriggerEvent
    UE5中用Python接口创建LevelSequence与设置TriggerEvent本文内容可能只能在UE5下有用,未在UE4环境下实验过。背景遇到了一个美术需求,需要批量读取一段动画,制......
  • 力扣525(java&python)-连续数组(中等)
    题目:给定一个二进制数组nums,找到含有相同数量的0和1的最长连续子数组,并返回该子数组的长度。 示例1:输入:nums=[0,1]输出:2说明:[0,1]是具有相同数量......
  • day13 I/O流——字节输入输出流、字符输入输出流 & File常用类 & (字节)复制大文件
    day13I/O流定义:数据在两设备传输称为流,流是一组有顺序的,有起点和终点的字节集合I是input的缩写,表示输入流O是output缩写,表示输出流字节流(视频等)输入InputStream......
  • 常用内置模块
    常用内置模块目录常用内置模块包编程思想的转变软件开发目录规范常用内置模块之collections模块常用内置模块之时间模块常用内置模块之随机数模块包什么是包?包是一个......
  • Python学习路程——Day18
    Python学习路程——Day18包的具体使用''' 虽然在python3中对包的要求低了,不需要__init__.py文件也可以识别,但是为了兼容性考虑,我们最好还是要加上__init__.py 1、如果......
  • springboot 常用的注解,解决面试
    一: ComponentScan :作用扫描二: MapperScan :扫描mapper 三: @SpringBootApplication组合注解四: @EnableAutoConfiguration开启自动配置的功能五: @AutoConfigurat......