合并到字典的Python程序。
在该程序中,给出了两个字典。我们的任务是合并这两个列表。这里我们使用update()方法。更新方法可以用于合并两个列表。在这里,第二个列表合并到第一个列表中。它不返回任何值,表示不创建任何新列表。
示例
Input::A= ['AAA',10]
B= ['BBB',20]
Output::
C= {'BBB': 20, 'AAA': 10}
算法
Step 1: First create two User input dictionary.Step 2: then use update() for merging. The second list is merged into the first list
Step 3: Display the final dictionary.
范例程式码
def Merge(dict1, dict2):return(dict2.update(dict1))
# Driver code
d1 = dict()d2=dict()
data = input('Enter Name & Roll separated by ":" ')
temp = data.split(':')
d1[temp[0]] = int(temp[1])
for key, value in d1.items():
print('Name: {}, Roll: {}'.format(key, value))
data = input('Enter Name & Roll separated by ":" ')
temp = data.split(':')
d2[temp[0]] = int(temp[1])
for key, value in d2.items():
print('Name: {}, Roll: {}'.format(key, value))
# This return None
(Merge(d1, d2))
print("Dictionary after merging ::>",d2)
输出结果
Enter Name & Roll separated by ":" AAA:10Name: AAA, Roll: 10
Enter Name & Roll separated by ":" BBB:20
Name: BBB, Roll: 20
Dictionary after merging ::> {'BBB': 20, 'AAA': 10}
以上是 合并到字典的Python程序。 的全部内容, 来源链接: utcz.com/z/322332.html