首页 > 解决方案 > 如何显示字典中的项目列表?

问题描述

问题要求通过定义一个名为print_room_items(room)I 的函数,我应该将一个房间作为输入并显示在这个房间中找到的项目列表。如果房间内没有物品,则不打印任何内容。

这是其中的2个房间:

room_reception = {
    "name": "Reception",
    "description": '768',
    "exits": {"south": "Admins", "east": "Tutor", "west": "Parking"},
    "items": [item_biscuits, item_handbook]
}
room_tutor = {
    "name": "your personal tutor's office",
    "description": '890',
    "exits": {"west": "Reception"},
    "items": []
}

我想出的代码是:

def print_room_items(room):
    room_item_01 = room['items'][0]['name']
    room_item_02 = room['items'][1]['name']
    print(room_item_01)
    print(room_item_02)

print_room_items(rooms["Reception"])

这样的代码看起来不是特别优雅。最重要的是,当我尝试为没有任何项目而不是没有输出的房间运行代码时,我确实遇到了错误。在这种情况下,导师室。

标签: pythonpython-3.x

解决方案


一种方法:

def print_room_items(room):
    for item in room ['items']:
        print(item)

或者,如果您需要打印的是“item ['name']”:

def print_room_items(room):
    for item in room ['items']:
        print(item['name'])

推荐阅读