用于更改字典中值的Python程序
给定Python中的字典,任务是编写一个Python程序来更改其中一个键值对中的值。本文讨论了有效执行此操作的机制。
例子:
Input: {'hari': 1, 'dita': 2}
Output: {'hari': 1, 'dita': 4}
Input: {'hari': 1, 'dita': 2}
Output: {'hari': 3, 'dita': 5}
改变字典的值
方法一
在这里,我们引用要更改的值的键并为其提供新值。
例子:
Python3
# declaring dictionary
dict = {'hari': 1, 'dita': 2}
# original dictionary
print("initial dictionary-", dict)
# changing the key value from 2 to 4
dict['dita'] = 4
# dictionary after update
print("dictionary after modification-", dict)
Python3
# declaring dictionary
dict1 = {'hari': 1, 'dita': 2}
# original dictionary
print("initial dictionary-", dict1)
# list of values which will replace the values of dict1
list1 = [3, 5]
# this preserves the keys and modifies the values
dict1 = dict(zip(list(dict1.keys()), list1))
# modified dictionary
print("dictionary after modification-", dict1)
输出:
initial dictionary- {‘hari’: 1, ‘dita’: 2}
dictionary after modification- {‘hari’: 1, ‘dita’: 4}
方法二:
在这个方法中,我们使用 zip()函数,它聚合迭代并将它们组合成一个元组形式。
例子:
蟒蛇3
# declaring dictionary
dict1 = {'hari': 1, 'dita': 2}
# original dictionary
print("initial dictionary-", dict1)
# list of values which will replace the values of dict1
list1 = [3, 5]
# this preserves the keys and modifies the values
dict1 = dict(zip(list(dict1.keys()), list1))
# modified dictionary
print("dictionary after modification-", dict1)
输出:
initial dictionary- {‘hari’: 1, ‘dita’: 2}
dictionary after modification- {‘hari’: 3, ‘dita’: 5}