📜  Python程序的输出 |第 9 集(字典)

📅  最后修改于: 2022-05-13 01:55:23.136000             🧑  作者: Mango

Python程序的输出 |第 9 集(字典)

先决条件:字典
1)以下程序的输出是什么?

Python3
dictionary = {'GFG' : 'geeksforgeeks.org',
              'google' : 'google.com',
              'facebook' : 'facebook.com'
              }
del dictionary['google'];
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)


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


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


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


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


a) b 和 d
b) 运行时错误
c) GFG
Facebook
d) 脸书
GFG
答。 (一种)
输出:

facebook
GFG

解释:语句: 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) 以下程序的输出是什么?

Python3

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

a) 编译错误
b) 运行时错误
c) ('谷歌', 1)
(“脸书”,2)
(“Youtube”,3)
(“微软”,2)
('GFG', 1)
d) 这些都不是
答。 (C)
说明: dictionary1.update(dictionary2) 用于用dictionary2 的条目更新dictionary1 的条目。如果两个字典中有相同的键,则使用第二个字典中的值。

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

Python3

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

a) 由于重复键导致的编译错误
b) 由于重复键导致的运行时错误
c) 3
d) 1
答。 (C)
解释:这里,GFG 是重复键。 Python中不允许重复键。如果字典中有相同的键,则最近分配的值将分配给该键。

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

Python3

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) 以上都不是
答。 (二)
说明:字典可以保存任何值,例如整数、字符串、列表,甚至是另一个保存键值对的字典。

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

Python3

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

a) 谷歌 3 GFG 1 Facebook 2
b) Facebook 2 GFG 1 谷歌 3
c) Facebook 2 谷歌 3 GFG 1
d) 上述任何一项

e) 以上都不是
答。 (e)

(e) 的解释:由于Python 3.7 字典是按插入顺序排序的。