我在python中使用字典时遇到问题。我可以不使用try / except块来解决这个问题吗?
dict1 = { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
list1 = [['k1', 'key1', 'info1'], ['k2', 'key2', 'info2'], ['k3', 'key3', 'info3'], 'k4', 'key4', 'info4']
for row in list1:
print(dict1[row[1]])
我希望输出仅输出字典中键的值,而do nothing
输出不存在的键
答案 0 :(得分:-1)
试试这个:
dict1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
list1 = [['k1', 'key1', 'info1'], ['k2', 'key2', 'info2'], ['k3', 'key3', 'info3'], 'k4', 'key4', 'info4']
for row in list1:
for col in row:
if col in dict1:
print(dict1[col])
另外,要获取keys
中的所有dict
:
for key in dict1.keys():
print(key)