1006- Python 字典(Dictionary) items()方法

本文详细介绍了Python中字典的基本操作,包括如何添加、修改和删除条目等,并通过具体的代码示例展示了如何进行这些操作。同时,文章还提供了一些实际应用场景的例子,如在超市购物场景中使用字典进行价格计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值