python字典改变value值方法总结

yipeiwu_com6年前Python基础

今天这篇文章中我们来了解一下python之中的字典,在这文章之中我会对python字典修改进行说明,以及举例说明如何修改python字典内的值。废话不多说,我们开始进入文章吧。

首先我们得知道什么是修改字典

修改字典

向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:

# !/usr/bin/python

 

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};

 

dict['Age'] = 8; # update existing entry

dict['School'] = "DPS School"; # Add new entry

 

print "dict['Age']: ", dict['Age'];

print "dict['School']: ", dict['School'];

以上实例输出结果:

dict['Age']: 8

dict['School']: DPS School

字典中的键存在时,可以通过字典名+下标的方式访问字典中改键对应的值,若键不存在则会抛出异常。如果想直接向字典中添加元素可以直接用字典名+下标+值的方式添加字典元素,只写键想后期对键赋值这种方式会抛出异常。

>> > a = ['apple', 'banana', 'pear', 'orange']

>> > a

['apple', 'banana', 'pear', 'orange']

>> > a = {1: 'apple', 2: 'banana', 3: 'pear', 4: 'orange'}

>> > a

{1: 'apple', 2: 'banana', 3: 'pear', 4: 'orange'}

>> > a[2]

'banana'

>> > a[5]

Traceback(most

recent

call

last):

File

"<pyshell#31>", line

1, in < module >

a[5]

KeyError: 5

>> > a[6] = 'grap'

>> > a

{1: 'apple', 2: 'banana', 3: 'pear', 4: 'orange', 6: 'grap'}

2.使用updata方法,把字典中有相应键的键值对添加update到当前字典>>> a

{1: 'apple', 2:'banana', 3: 'pear', 4: 'orange', 6: 'grap'}

  

>>>a.items()

  

dict_items([(1,'apple'), (2, 'banana'), (3, 'pear'), (4, 'orange'), (6, 'grap')])

  

>>>a.update({1:10,2:20})

  

>>> a

  

{1: 10, 2: 20,3: 'pear', 4: 'orange', 6: 'grap'}

  

#{1:10,2:20}替换了{1: 'apple', 2: 'banana'}

相关文章

浅谈python为什么不需要三目运算符和switch

对于三目运算符(ternary operator),python可以用conditional expressions来替代 如对于x<5?1:0可以用下面的方式来实现...

详解supervisor使用教程

详解supervisor使用教程

A Process Control System 使用b/s架构、运行在类Unix系统上一个进程监控管理系统它可以使进程以daemon方式运行,并且一直监控进程,在意外退出时能自动重启进...

Python的mysql数据库的更新如何实现

Python的mysql数据库的更新           Python的mysql数据库的更新操...

python的re模块使用方法详解

一、正则表达式的特殊字符介绍 正则表达式 ^ 匹配行首 $ 匹配行尾 . 任意...

Python的pycurl包用法简介

pycurl是功能强大的python的url包,是用c语言写的,速度很快,比urllib和httplib都快 调用方法: import pycurl c = pycurl.Curl...