【发布时间】:2020-05-24 08:04:11
【问题描述】:
我是 Python 的新手,我对使用 .formkeys() 方法和列表感到困惑。
下面是我的代码:
# dictionary exercise 4: Initialize dictionary with default values
employees = ['Kelly', 'Emma', 'John']
defaults = {"designation": 'Application Developer', "salary": 8000}
def_dictionary = dict()
def_dictionary.setdefault("designation", "Application Developer")
def_dictionary.setdefault("salary", 8000)
print(def_dictionary)
res_dict = dict.fromkeys(employees[0], defaults)
print(res_dict)
print(res_dict)
这里的输出是
{'K': {'designation': 'Application Developer', 'salary': 8000}, 'e': {'designation': 'Application Developer', 'salary': 8000}, 'l': {'designation': 'Application Developer', 'salary': 8000}, 'y': {'designation': 'Application Developer', 'salary': 8000}}
我想做的是将员工“Kelly”与默认值字典配对,但是,我不明白为什么我将 'K'、'E'、'L'、'Y' 字符串作为我的键res_dict。
我知道解决方案应该是
res_dict = dict.fromkeys(employees, defaults)
我只是想知道为什么代码将 Kelly 解析为“K”、“E”、“L”、“Y”。
谢谢
【问题讨论】:
-
请注意,您的示例中的
defaults是一个可变值(dict),因此当您使用dict.fromkeys中的value选项时,每个条目将具有相同的值。稍后,当您修改一个值时,它将针对 所有实例 进行更改。相反,您应该使用dict.fromkeys(employees, defaults.copy())之类的东西。 -
请注意,您可能想要做一个基本的 Python 教程,介绍核心数据类型以及如何使用它们。例如,
def_dictionary.setdefault要么不做你认为它做的事,要么不应该用于你想让它做的事。要存储键值对,请使用def_dictionary["designation"] = "Application Developer"- 或在使用{key: value, ...}文字创建字典时存储它。此外,当多个对象具有相同类型的数据时,请考虑使用class- 特别是dataclass或NamedTuple。
标签: python list mergeddictionaries