美文网首页
Python 字典学习

Python 字典学习

作者: 印象iOS | 来源:发表于2018-05-16 16:31 被阅读0次

dict_1 = {'a' : 1, 'b' : 2, 'c' : 3}

#1. 根据键获得值
if 'd' in dict_1.keys(): #键不存在会报错
    print(dict_1['d'])

#2. 修改键对应的值
dict_1['a'] = 100
print(dict_1)

#3. 字典增加元素
dict_1['d'] = 34
print(dict_1)

#4.删除字典元素,删除字典
del dict_1['a'] #删除a对应的键值对
dict_1.clear()  #情况字典所有条目
del dict_1      #删除字典


dict_1 = {'a' : 1, 'b' : 2, 'c' : 3}

#5. 字典中的条目个数
print(len(dict_1))

#6.删除字典所有的元素
dict_1.clear()
print(dict_1)


dict_1 = {'a' : 1, 'b' : 2, 'c' : 3}
#7.字典浅复制
dict_2 = dict_1.copy()
dict_2['a'] = 5
print(dict_1, dict_2)

#8. 用列表生成一个同一值的字典
list_1 = ['a', 'b', 'c']
dict_3 = dict.fromkeys(list_1, 2)
print(dict_3)

#9. 返回指定键的值,不存在返回默认值
print(dict_1.get('a'))
print(dict_1.get('d', 123))

#10.返回以元组为元素的列表
list_2 = dict_1.items()
print(list_2)

#11.返回所有键的列表
print(dict_1.keys())

#12.如果键不存在,添加键并设置值为默认值
dict_1.setdefault('d', 34)
print(dict_1)

#13. 把其他字典更新到字典中
dict_4 = {'z' : 50}
dict_1.update(dict_4)
print(dict_1)

#14. 以列表的形式返回所有的值
print(dict_1.values())

#15.删除指定键对应的值
dict_1.pop('f', 111)
print(dict_1)

#16.随机删除一个键值对
dict_1.popitem()
print(dict_1)

相关文章

  • Day01自学 - Python 字典(Dictionary)

    学习参考博客地址:Python 字典(Dictionary) | Python 优雅的操作字典 一、创建字典 字典...

  • Python学习3

    python 学习三 字典

  • 2018-06-29

    python学习 学习python字符串、列表、元组、字典、日期和时间模块

  • 读书笔记 | Python学习之旅 Day4

    Python学习之旅 读书笔记系列 Day 4 《Python编程从入门到实践》 第6章 字典 知识点 字典:相互...

  • Python学习-字典(dict)

    查看所有Python相关学习笔记 字典(dict) 字典内元素是无序的 新增(创建)字典(key-value) k...

  • Python学习——字典

    Python学习——字典 字典的外在样式如: { },字典内可包含各种数据,例如列表、字典,且其中以键值对的形式展...

  • Python 字典学习

  • python学习----字典

    代码如下 输出结果如下:

  • Python 字典学习

    创建字典的两种方法: dict dict 访问字典中元素的两种方法: '山山' '山山' 判断字典是否存在某一元素...

  • 2018-10-30

    Python字典学习 在Python中,列表和字典常用于存储数据。 日常生活中,经常会去买饮料。饮料有果汁、咖啡、...

网友评论

      本文标题:Python 字典学习

      本文链接:https://www.haomeiwen.com/subject/rjtmdftx.html