本日这篇文章中我们来相识一下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字典怎样转变value值的细致内容,更多请关注ki4网别的相干文章!