Python字典
时间:2020-02-23 14:42:38 来源:igfitidea点击:
今天,我们将学习Python词典。
先前我们了解了Python Set。
Python字典
python字典基本上是键-值对的序列。
这意味着,对于每个键,都应该有一个值。
所有键都是唯一的。
我们可以初始化一个用花括号关闭的字典。
键和值之间用分号分隔,值之间用逗号分隔。
字典易于使用。
以下代码将帮助您了解Python词典。
my_dictionary = {} #init empty dictionary
#init dictionary with some key-value pair
another = {
#key : value,
'man' : 'Bob',
'woman' : 'Alice',
'other' : 'Trudy'
}
#print initial dictionaries
print(my_dictionary)
print(another)
#insert value
my_dictionary['day']='Thursday'
another['day']='Thursday'
my_dictionary['color']='Blue'
another['color']='Blue'
#print updated dictionaries
print('Updated Dictionaries:')
print(my_dictionary)
print(another)
#update values
my_dictionary['day']='Friday'
another['day']='Friday'
my_dictionary['color']='Black'
another['color']='Black'
#print updated dictionaries
print('After Update:')
print(my_dictionary)
print(another)
#printing a single element
print(my_dictionary['day'])
print(another['color'])
以下代码的输出将是
{}
{'woman': 'Alice', 'other': 'Trudy', 'man': 'Bob'}
Updated Dictionaries:
{'color': 'Blue', 'day': 'Thursday'}
{'color': 'Blue', 'woman': 'Alice', 'other': 'Trudy', 'day': 'Thursday', 'man': 'Bob'}
After Update:
{'color': 'Black', 'day': 'Friday'}
{'color': 'Black', 'woman': 'Alice', 'other': 'Trudy', 'day': 'Friday', 'man': 'Bob'}
Friday
Black
>>>
访问Python字典
我们可以通过键访问字典元素。
如果键未知,则可以使用for循环遍历字典元素。
dictionary = {
'name' : 'Alex',
'age' : 23,
'sex' : 'male'
}
#method1
print('Method1')
#fetch all the keys of that dictionary
key_list = dictionary.keys() #store the key list in key_list
#print to see the keys
print('list of keys')
print(key_list)
#pick key from the key_list
for key in key_list:
#print the specific value for the key
print('key = '+key+' value = '+str(dictionary[key]))
#method2
print('\nMethod2')
#pick key from directly from the dictionary
for key in dictionary:
#print the specific value for the key
print('key = '+key+' value = '+str(dictionary[key]))
它将产生以下输出
Method1 list of keys ['age', 'name', 'sex'] key = age value = 23 key = name value = Alex key = sex value = male Method2 key = age value = 23 key = name value = Alex key = sex value = male >>>
从Python字典中删除元素
删除python字典中的元素非常容易。
您可以只使用del关键字。
它将从Python字典中删除单个元素。
但是,如果要删除字典中的所有元素。
您可以使用clear()函数。
以下代码显示了从Python Dictionary中删除元素的方法:
dictionary = {
'name' : 'Alex',
'age' : 23,
'sex' : 'male'
}
#print initial dictionary
print(dictionary)
#delete a single element
del dictionary['name']
print('After deleting name')
print(dictionary)
'''
you cannot the element which is not in the dictionary. so the below statement
will raise an error
del dictionary['name']
'''
#delete all elements from the list
dictionary.clear()
print(dictionary) #this will show an empty dictionary
#delete the entire variable
del dictionary
print(dictionary) #this will produce error

