【Python 笔记1】字典

1. 前言

想象你手头有一本非常厚的食谱书,这本书里面收集了来自世界各地的菜肴配方。书的每一页都详细描述了如何准备一个特定的菜肴,包括所需的原料、准备步骤、烹饪时间等。现在,为了更方便地查找和管理这些食谱,你决定将它们整理进一个大型的数字化数据库——这就是我们的“复杂字典”。

在这个“复杂字典”中,每个“键”是一个菜肴的名字,而每个“键”对应的“值”是一个包含所有相关信息的小字典,这个小字典里面包含了原料、准备步骤、烹饪时间等。

例如,如果你想查找“意大利面”的配方,你只需要在你的复杂字典中找到“意大利面”这个键。这个键会指向另一个包含了所有制作意大利面所需信息的字典,比如:

  • 原料:意大利面、番茄、大蒜、橄榄油、盐、胡椒粉。
  • 准备步骤:详细描述了如何将原料准备好并烹饪成一盘美味的意大利面。
  • 烹饪时间:30分钟。

这样,无论你想查找的是意大利面、寿司还是印度咖喱,你都可以通过这个复杂字典快速获得所有必要的信息,从而在家准备出地道的多国料理。

但是,你的食谱集不仅仅停留在这里。你还决定为每个国家创建一个子字典,将属于同一国家的菜肴集中在一起。这样,当你想尝试意大利菜时,你可以直接查看意大利的子字典,里面会列出所有的意大利菜肴和它们对应的食谱。

2. 普通字典

2.1 创建和初始化字典

# 创建一个空字典
my_dict = {}

# 创建一个带有初始键值对的字典
person = {
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

2.2 访问字典中的值

# 获取字典中的值
print(person["name"])  # 输出: John Doe

# 使用get方法,如果键不存在,可以返回一个默认值
print(person.get("country", "Unknown"))  # 输出: Unknown

2.3 修改和添加键值对

# 修改字典中的值
person["age"] = 31

# 添加新的键值对
person["email"] = "johndoe@example.com"

2.4 删除键值对

# 删除一个键值对
del person["age"]

# 使用pop方法删除并返回值
email = person.pop("email")
print(email)  # 输出: johndoe@example.com

2.5 遍历字典

# 遍历所有键值对
for key, value in person.items():
    print(f"{key}: {value}")

# 输出:
# name: John Doe
# city: New York

2.6 字典推导式

字典推导式是创建字典的一种快捷方式,允许从一个可迭代对象构造字典。

# 以一个字符串列表创建一个字典,其中列表中的字符串作为键,它们的长度作为值
words = ["apple", "banana", "cherry"]
word_length = {word: len(word) for word in words}
print(word_length)  # 输出: {'apple': 5, 'banana': 6, 'cherry': 6}

3. 嵌套字典

字典中可以包含另一个字典,这使得可以构建更复杂的数据结构。

# 创建一个包含嵌套字典的字典
users = {
    "user1": {
        "name": "John",
        "age": 22,
        "email": "john@example.com"
    },
    "user2": {
        "name": "Marie",
        "age": 28,
        "email": "marie@example.com"
    }
}

# 访问嵌套字典中的值
print(users["user1"]["name"])  # 输出: John

4. 应用示例

# 假设我们要创建一个复杂的食谱集字典,其中包含不同国家的菜肴及其详细配方

# 定义食谱集字典
recipe_book = {
    "Italy": {
        "Spaghetti Carbonara": {
            "ingredients": ["Spaghetti", "Bacon", "Parmesan Cheese", "Eggs"],
            "steps": [
                "Cook spaghetti in a large pot of boiling water.",
                "Fry bacon until crisp.",
                "Beat eggs and Parmesan together, then mix with bacon.",
                "Combine egg mixture with spaghetti."
            ],
            "cooking_time": "20 minutes"
        },
        "Margherita Pizza": {
            "ingredients": ["Pizza Dough", "Tomato Sauce", "Mozzarella Cheese", "Basil"],
            "steps": [
                "Spread tomato sauce over pizza dough.",
                "Add slices of mozzarella cheese.",
                "Bake in preheated oven until crust is golden.",
                "Garnish with basil leaves before serving."
            ],
            "cooking_time": "30 minutes"
        }
    },
    "Japan": {
        "Sushi": {
            "ingredients": ["Sushi Rice", "Nori", "Fresh Fish", "Soy Sauce", "Wasabi"],
            "steps": [
                "Prepare sushi rice.",
                "Lay out Nori and spread sushi rice on it.",
                "Place slices of fish on top of the rice.",
                "Roll the Nori and slice into pieces."
            ],
            "cooking_time": "45 minutes"
        }
    }
}

# 函数来打印指定国家的所有菜肴配方
def print_recipes_by_country(country):
    if country in recipe_book:
        print(f"Recipes from {country}:")
        for dish, details in recipe_book[country].items():
            print(f"\n{dish}")
            print("Ingredients:")
            for ingredient in details["ingredients"]:
                print(f"- {ingredient}")
            print("\nSteps:")
            for step in details["steps"]:
                print(f"- {step}")
            print(f"\nCooking Time: {details['cooking_time']}\n")
    else:
        print(f"No recipes found for {country}.")

# 打印意大利的食谱
print_recipes_by_country("Italy")

# 打印日本的食谱
print_recipes_by_country("Japan")

上述的字典recipe_book[country] 也可以用来赋值,等等

相关推荐

  1. Python 笔记1字典

    2024-04-03 18:44:02       24 阅读
  2. Python基础学习笔记(十二)——字典

    2024-04-03 18:44:02       9 阅读
  3. python字典

    2024-04-03 18:44:02       17 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-03 18:44:02       5 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-03 18:44:02       5 阅读
  3. 在Django里面运行非项目文件

    2024-04-03 18:44:02       4 阅读
  4. Python语言-面向对象

    2024-04-03 18:44:02       7 阅读

热门阅读

  1. Power Automate里的常用方法

    2024-04-03 18:44:02       20 阅读
  2. Kingbase简单存储过程

    2024-04-03 18:44:02       23 阅读
  3. 设计模式 - Provider 模式

    2024-04-03 18:44:02       23 阅读
  4. dotnet依赖注入与IOC(包含Autofac的使用)

    2024-04-03 18:44:02       25 阅读
  5. TS小记--

    2024-04-03 18:44:02       20 阅读
  6. 什么是json?json可以存放哪几种数据类型

    2024-04-03 18:44:02       20 阅读