• 难度级别: 简单

1) 以下程序的输出是什么?

dictionary = {'haiyong' : 'haiyong.site',
'baidu' : 'baidu.com',
'juejin' : 'juejin.cn'
}
del dictionary['baidu'];
for key, values in dictionary.items():
print(key)
dictionary.clear();
for key, values in dictionary.items():
print(key)
del dictionary;
for key, values in dictionary.items():
print(key)

a) b 和 d 

b) 运行时错误 

c) haiyong 

juejin 

d) juejin 

haiyong

答案. (a)

输出:

juejin
haiyong

解释: 语句:del dictionary; 删除整个字典,因此迭代已删除的字典会引发运行时错误,如下所示:

Traceback (most recent call last):
File "cbeac2f0e35485f19ae7c07f6b416e84.py", line 12, in
for key, values in dictionary.items():
NameError: name 'dictionary' is not defined

2) 以下程序的输出是什么?

dictionary1 = {'Google' : 1,
'Facebook' : 2,
'Microsoft' : 3
}
dictionary2 = {'Haiyong' : 1,
'Microsoft' : 2,
'Youtube' : 3
}
dictionary1.update(dictionary2);
for key, values in dictionary1.items():
print(key, values)

a) 编译错误 

b) 运行时错误 

c) ('Google', 1) 

('Facebook', 2) 

('Youtube', 3) 

('Microsoft', 2) 

('Haiyong', 1) 

d) 这些都不是

答案.(c)

解释:  dictionary1.update(dictionary2) 用于用dictionary2 的条目更新dictionary1 的条目。如果两个字典中有相同的键,则使用第二个字典中的值。

3) 以下程序的输出是什么?

dictionary1 = {'Haiyong' : 1,
'Google' : 2,
'Haiyong' : 3
}
print(dictionary1['Haiyong']);

a) 由于重复键导致的编译错误 

b) 由于重复键导致的运行时错误 

c) 3 

d) 1

答案. (c)

解释: 这里,Haiyong 是重复键。python中不允许重复键。如果字典中有相同的键,则最近分配的值将分配给该键。

4) 以下程序的输出是什么?

temp = dict()
temp['key1'] = {'key1' : 44, 'key2' : 566}
temp['key2'] = [1, 2, 3, 4]
for (key, values) in temp.items():
print(values, end = "")

a) 编译错误 

b) {'key1': 44, 'key2': 566}[1, 2, 3, 4] 

c) 运行时错误 

d) 以上都不是

答案. (b) 

解释: 字典可以保存任何值,例如整数、字符串、列表,甚至是另一个保存键值对的字典。 

5) 以下 Python 程序的输出是什么?

temp = {'Haiyong' : 1,
'Facebook' : 2,
'Google' : 3
}
for (key, values) in temp.items():
print(key, values, end = " ")

a) Google 3 Haiyong 1 Facebook 2 

b) Facebook 2 Haiyong 1 Google 3 

c) Facebook 2 Google 3 Haiyong 1 

d) 上述任何一个

e) 以上都不是

答案. (e)

(e) 的解释: 因为 python 3.7 字典是按插入顺序排序的。

如果大家发现任何不正确的地方,可以在下方评论区告诉我,互相学习,共同进步!