Python 字典的一些操作
目录
用 [TOC]
来生成目录:
字典基础
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
dict = {‘Alice’: ‘2341’, ‘Beth’: ‘9102’, ‘Cecil’: ‘3258’}
Markdown及扩展
代码块
inventory = {
'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}
# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']
# Sorting the list found under the key 'pouch'
inventory['pouch'].sort()
# Your code here
inventory['pocket']=['seashell','strange berry','lint']
inventory['backpack'].sort()
inventory['backpack'].remove('dagger')
inventory['gold'] += 50
Instructions
01.Add a key to inventory called 'pocket'
02.Set the value of 'pocket' to be a list consisting of the strings 'seashell', 'strange berry', and 'lint'
03..sort() the items in the list stored under the 'backpack' key
04.Then .remove('dagger') from the list of items stored under the 'backpack' key
05.Add 50 to the number stored under the 'gold' key