This section mainly records python Some functions in the dictionary use
Tips : The following is the main body of this article
Case description : With fruit Take the dictionary describing fruit as an example
The copied new dictionary will not affect the original dictionary
fruits = {
'apple': 30,
'banana': 50,
'pear': 100
}
real_fruits = fruits.copy()
print(real_fruits)
real_fruits['orange'] = 50
real_fruits.update({
'cherry': 100})
print(real_fruits)
real_fruits['apple'] = real_fruits['apple'] - 5
print(real_fruits)
real_fruits['pear'] -= 3
print(real_fruits)
real_fruits.clear()
print(real_fruits)
print(" the second day ")
real_fruits = fruits.copy()
print(real_fruits)
Running results
{
'apple': 30, 'banana': 50, 'pear': 100}
{
'apple': 30, 'banana': 50, 'pear': 100, 'orange': 50, 'cherry': 100}
{
'apple': 25, 'banana': 50, 'pear': 100, 'orange': 50, 'cherry': 100}
{
'apple': 25, 'banana': 50, 'pear': 97, 'orange': 50, 'cherry': 100}
{
}
the second day
{
'apple': 30, 'banana': 50, 'pear': 100}
Routine usage in and not in
default_dict = {
'a': None, 'b': 1, 'c': 0, 'd': ''}
print('a' in default_dict)
print(bool(default_dict.get('a')))
# get Boolean operations with values
print(bool(default_dict.get('b')))
print('f' in default_dict)
print('f' not in default_dict)
Running results
True
False
True
False
True
function : Delete the last set of key value pairs in the current dictionary and return
usage : see case
matters needing attention : If the dictionary is empty, an error is reported
# case
students = {
'dewei': ' To ', 'xiaomu': ' stay ', 'xiaoyun': ' Are you there? ', 'xiaogao': ' stay '}
print('xiaogao are you there ')
xiaogao = students.popitem()
print('{} shout {}'.format(xiaogao[0], xiaogao[1]))
print('xiaoyun are you there ')
xiaoyun = students.popitem()
print('{} shout {}'.format(xiaoyun[0], xiaoyun[1]))
print('xiaomu are you there ')
xiaomu = students.popitem()
print('{} shout {}'.format(xiaomu[0], xiaomu[1]))
print('dewei are you there ')
dewei = students.popitem()
print('{} shout {}'.format(dewei[0], dewei[1]))
print(students)
Running results :
xiaogao are you there
xiaogao shout stay
xiaoyun are you there
xiaoyun shout Are you there?
xiaomu are you there
xiaomu shout stay
dewei are you there
dewei shout To
{
}
Tips : Here is a summary of the article :
This section mainly records the common operations of the dictionary