Python 字典的一些操作
目录
用 [TOC]来生成目录:
字典基础
http://www.runoob.com/python/python-dictionary.html
Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。
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
#A Day at the Supermarket
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
# Write your code below!
def compute_bill(food):
total=0
for item in food:
total =total + prices[item] # not food[item]
return total
本文详细介绍了Python中字典的基本操作,包括如何添加、修改和删除条目等,并通过具体的代码示例展示了如何进行这些操作。同时,文章还提供了一些实际应用场景的例子,如在超市购物场景中使用字典进行价格计算。
2万+

被折叠的 条评论
为什么被折叠?



