定义

info = {'name': '班长', 'id': 88, 'sex': 'man', 'address': '地球亚洲中国北京'}

print(info['name'])
print(info['address']) # 若访问不存在的键,则会报错
# print(info['age'])
# 不确定字典中是否存在某个键而又想获取其值时,使用get方法,还可以设置默认值
print(info.get('age',22))

字典的操作

修改

info = {'name': '班长', 'id': 100, 'sex': 'f', 'address': '地球亚洲中国北京'}
info['id'] = int(150301016)
print('修改之后的id为:%d' % info['id'])

添加

info = {'name': '班长', 'sex': 'f', 'address': '地球亚洲中国北京'}
info['id'] = int(150301016)
print('添加之后的id为:%d' % info['id'])

删除

# 删除指定的元素
info = {'name': '班长', 'sex': 'f', 'address': '地球亚洲中国北京'}
del info['name']
info.get("name") # 删除整个字典
info = {'name': 'monitor', 'sex': 'f', 'address': 'China'}
del info
print(info)
# NameError: name 'info' is not defined # 清空整个字典
info = {'name': 'monitor', 'sex': 'f', 'address': 'China'}
info.clear()
print(info)
# {}

相关方法

info = {'name': 'monitor', 'sex': 'f', 'address': 'China'}

# 键值对的个数
print(len(info))
# # 返回一个包含字典所有KEY的列表
print(info.keys())
# dict_keys(['name', 'sex', 'address']) # 返回一个包含字典所有value的列表
print(info.values())
# dict_values(['monitor', 'f', 'China']) # 返回一个包含所有(键,值)元组的列表
print(info.items())
# dict_items([('name', 'monitor'), ('sex', 'f'), ('address', 'China')]) # 如果key在字典中,返回True,否则返回False
print("x" in info)
# False

遍历

info = {'name': 'monitor', 'sex': 'f', 'address': 'China'}

# 遍历字典的key
for key in info.keys():
print(key, end=" ")
# name sex address # 遍历字典的value
for val in info.values():
print(val, end=" ")
# monitor f China # 遍历字典的元素
for item in info.items():
print(item, end=" ")
# ('name', 'monitor') ('sex', 'f') ('address', 'China') # 遍历字典的key-value
for key, val in info.items():
print("k=%s,v=%s" % (key, val), end=" ")
# k=name,v=monitor k=sex,v=f k=address,v=China

其他遍历

# 带下标索引的遍历
chars = ['a', 'b', 'c', 'd']
i = 0
for chr in chars:
print("%d %s" % (i, chr))
i += 1
for i, chr in enumerate(chars):
print(i, chr)

# 字符串遍历
a_str = "hello swt"
for char in a_str:
print(char, end=' ')
# h e l l o s w t # 列表遍历
a_list = [1, 2, 3, 4, 5]
for num in a_list:
print(num, end=' ')
# 1 2 3 4 5 # 元组遍历
a_turple = (1, 2, 3, 4, 5)
for num in a_turple:
print(num, end=" ")
# 1 2 3 4 5

5、Python-字典的更多相关文章

  1. Python字典和集合

    Python字典操作与遍历: 1.http://www.cnblogs.com/rubylouvre/archive/2011/06/19/2084739.html 2.http://5iqiong. ...

  2. python 字典排序 关于sort()、reversed()、sorted()

    一.Python的排序 1.reversed() 这个很好理解,reversed英文意思就是:adj. 颠倒的:相反的:(判决等)撤销的 print list(reversed(['dream','a ...

  3. python字典中的元素类型

    python字典默认的是string item={"browser " : 'webdriver.irefox()', 'url' : 'http://xxx.com'} 如果这样 ...

  4. python字典copy()方法

    python 字典的copy()方法表面看就是深copy啊,明显独立 d = {'a':1, 'b':2} c = d.copy() print('d=%s c=%s' % (d, c)) Code1 ...

  5. python 字典实现类似c的switch case

    #python 字典实现类似c的switch def print_hi(): print('hi') def print_hello(): print('hello') def print_goodb ...

  6. python字典的常用操作方法

    Python字典是另一种可变容器模型(无序),且可存储任意类型对象,如字符串.数字.元组等其他容器模型.本文章主要介绍Python中字典(Dict)的详解操作方法,包含创建.访问.删除.其它操作等,需 ...

  7. Python 字典(Dictionary)操作详解

    Python 字典(Dictionary)的详细操作方法. Python字典是另一种可变容器模型,且可存储任意类型对象,如字符串.数字.元组等其他容器模型. 一.创建字典 字典由键和对应值成对组成.字 ...

  8. Python 字典(Dictionary) get()方法

    描述 Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值. 语法 get()方法语法: dict.get(key, default=None) 参数 ...

  9. Python 字典(Dictionary) setdefault()方法

    描述 Python 字典(Dictionary) setdefault() 函数和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值. 语法 setdefault()方法语法: ...

  10. python 字典内置方法get应用

    python字典内置方法get应用,如果我们需要获取字典值的话,我们有两种方法,一个是通过dict['key'],另外一个就是dict.get()方法. 今天给大家分享的就是字典的get()方法. 这 ...

随机推荐

  1. 阅读<构建之法>第10、11、12章

    第10章 典型用户和场景 10.2 规格说明书 10.3 功能驱动的设计 问题:怎样写好spec?功能驱动设计的功能设计阶段怎样实现一个具体的功能? 第11章 软件设计与实现 11.2开发阶段的日常管 ...

  2. 如何批量删除Docker中已经停止的容器

    如何批量删除Docker中已经停止的容器   方法一: #显示所有的容器,过滤出Exited状态的容器,取出这些容器的ID, sudo docker ps -a|grep Exited|awk '{p ...

  3. k8s master 节点加入到可以调配node节点中的命令

    kubectl taint nodes --all node-role.kubernetes.io/master- 应该就可以了  效果再观察 效果为

  4. Vue 初识Vue

    <!DOCTYPE html><html lang="zh-cn"><head> <meta charset="utf-8&qu ...

  5. linux 单引号,双引号,反引号的小总结。

    还是老惯例说说事情的起因,由于最开始对linux下面的各种引号并不是特别敏感,导致有一天我在添加数据库字段的时候出现的错误,当时出现错误的原因是我在最外层使用了单引号进行包裹,然后一句话里面需要转意的 ...

  6. Delphi.XE2破解方法

    我安装的是Delphi.XE2.RTM.v16.0.4256.43595.Lite.v5.0 ,安装完后打开显示是15天试用. 退出XE2后把C:\Program Files\Embarcadero\ ...

  7. 在Delphi中调用"数据链接属性"对话框设置ConnectionString

    项目需要使用"数据链接属性"对话框来设置ConnectionString,查阅了一些资料,解决办法如下: 1.Delphi 在Delphi中比较简单,步骤如下: 方法1: use ...

  8. python之count()函数

    # count()统计字符串中特定单词或短语出现次数(n = 3) strs = 'Good! Today is good day! Good job!' n = strs.lower().count ...

  9. FFT ip core

    The FFT core provides four architecture options to offer a trade-off权衡取舍 between core size andtransf ...

  10. linux 环境下 firefox乱码问题解决

    https://blog.csdn.net/wlwlwlwl015/article/details/51482065