【问题标题】:Merging lists and dicts in Python with fromkeys() method使用 fromkeys() 方法在 Python 中合并列表和字典
【发布时间】: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 - 特别是dataclassNamedTuple

标签: python list mergeddictionaries


【解决方案1】:

employees[0]str "Kelly"str 对象是可迭代的 - 它会按顺序为您提供每个字符,例如

for c in "Kelly":
    print(c)

生产:

K
e
l
l
y

因此,当您调用 dict.fromkeys("Kelly", None) 时,您会获得“Kelly”中每个字符的密钥。

【讨论】:

    【解决方案2】:

    Sine dict.fromkeys(employees,defaults) 对employees 中的每个元素进行迭代,employees[0] 会将每个迭代的第 0 个索引作为键传递。

    employees = ['Kelly', 'Emma', 'John']
    defaults = {"designation": 'Application Developer', "salary": 8000}
    d = {}
    key = [employees[0]]
    d = d.fromkeys(key,defaults)
    print(d)
    

    会给你所需的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2012-08-11
      • 2012-07-17
      • 2015-01-10
      • 2016-09-25
      相关资源
      最近更新 更多