1

我是 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”。

谢谢

4

2 回答 2

2

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

for c in "Kelly":
    print(c)

产生:

K
e
l
l
y

所以,当你打电话时,dict.fromkeys("Kelly", None)你会得到“凯利”中每个角色的钥匙。

于 2020-05-24T08:09:28.900 回答
1

正弦 dict.fromkeys(employees,defaults) 迭代员工中的每个元素,employees[0] 将每个可迭代的第 0 个索引作为键传递。

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

会给你你需要的答案。

于 2020-05-24T08:56:50.297 回答