【问题标题】:How to create Multi Dimensional Dictionary如何创建多维字典
【发布时间】:2020-05-15 07:04:16
【问题描述】:

如何制作具有多个键和值的多维字典以及如何打印其键和值?

从这种格式:

main_dictionary= { Mainkey: {keyA: value
                             keyB: value
                             keyC: value
                 }}

我尝试这样做,但它给了我制造商的错误。这是我的代码

car_dict[manufacturer] [type]= [( sedan, hatchback, sports)]

这是我的错误:

File "E:/Programming Study/testupdate.py", line 19, in campany
car_dict[manufacturer] [type]= [( sedan, hatchback, sports)]
KeyError: 'Nissan'

我的打印代码是:

            for manufacuted_by, type,sedan,hatchback, sports in cabuyao_dict[bgy]:
                print("Manufacturer Name:", manufacuted_by)
                print('-' * 120)
                print("Car type:", type)
                print("Sedan:", sedan)
                print("Hatchback:", hatchback)
                print("Sports:", sports)

谢谢!我是 Python 新手。

【问题讨论】:

  • 如果您的代码引发“错误”,请包括实际错误和提供该错误的代码。我们无法确定您遇到的实际错误是什么,因此如果不猜测问题实际是什么,我们就无法真正帮助您。

标签: python-3.x dictionary multidimensional-array printing key


【解决方案1】:

我认为您对 dict 的工作原理以及如何“回调”其中的值有一点误解。

让我们举两个例子来说明如何创建数据结构:

car_dict = {}
car_dict["Nissan"] = {"types": ["sedan", "hatchback", "sports"]}
print(car_dict) #  Output: {'Nissan': {'types': ['sedan', 'hatchback', 'sports']}}

from collections import defaultdict
car_dict2 = defaultdict(dict)
car_dict2["Nissan"]["types"] = ["sedan", "hatchback", "sports"]
print(car_dict2) # Output: defaultdict(<class 'dict'>, {'Nissan': {'types': ['sedan', 'hatchback', 'sports']}})

在上面的两个示例中,我首先创建了一个字典,然后在添加我希望它包含的值之后的行上。在第一个示例中,我将 car_dict 赋予 key "Nissan" 并将其值设置为包含一些值的新字典。

在第二个示例中,我使用defaultdict(dict),其基本逻辑是“如果我没有为key 提供value,则使用工厂(dict) 为其创建value

你能看出在这两种不同方法中如何初始化值的区别吗?

当您在代码中调用car_dict[manufacturer][type] 时,您尚未启动car_dict["Nissan"] = value,因此当您尝试检索它时,car_dict 返回了KeyError

至于打印出值,你可以这样做:

for key in car_dict:
    manufacturer = key
    car_types = car_dict[key]["types"]
    print(f"The manufacturer '{manufacturer}' has the following types:")
    for t in car_types:
        print(t)

输出:

The manufacturer 'Nissan' has the following types:
sedan
hatchback
sports

当您循环通过dict 时,您将循环通过默认包含在其中的键。这意味着我们必须在循环内部检索key 的值,才能正确地print


另外作为一个附注:你应该尽量避免使用内置的名称,如type 作为变量名,因为你会覆盖该函数的命名空间,并且在将来你必须这样做时可能会遇到一些问题变量类型的比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 2018-07-24
    • 2016-03-18
    • 2013-05-03
    • 2014-04-19
    • 2021-12-07
    • 2014-11-13
    相关资源
    最近更新 更多