0

我想创建一个包含列表字典的新字典。我的代码是:

SERVICES = "FTP Download", "FTP Upload", "HTTP"
received = dict.fromkeys(SERVICES , {'MS1':[]})
n = 0
for service in SERVICES:
    received[service]['MS1'].append(n)
    n += 1
print(received)

我得到了什么。尽管我使用了不同的键,但我在每本字典中都得到了相同的列表。

我的输出是:{'FTP Download': {'MS1': [0, 1, 2]}, 'HTTP': {'MS1': [0, 1, 2]}, 'FTP Upload': {'MS1': [0, 1, 2]}}

从键创建空白字典的正确方法是什么?

4

1 回答 1

1

我会简单地使用字典理解:

>>> SERVICES = "FTP Download", "FTP Upload", "HTTP"
>>> received = {k: {'MS1': []} for k in SERVICES}
>>> received
{'FTP Download': {'MS1': []}, 'HTTP': {'MS1': []}, 'FTP Upload': {'MS1': []}}
>>> received["HTTP"]["MS1"].append(17)
>>> received
{'FTP Download': {'MS1': []}, 'HTTP': {'MS1': [17]}, 'FTP Upload': {'MS1': []}}

由于fromkeys使用v每个键的值,received = dict.fromkeys(SERVICES , {'MS1':[]})实际上只MS1涉及一个字典,这就是您注意到的:

>>> received = dict.fromkeys(SERVICES , {'MS1':[]})
>>> received.values()
dict_values([{'MS1': []}, {'MS1': []}, {'MS1': []}])
>>> [id(v) for v in received.values()]
[141458940, 141458940, 141458940]
于 2012-09-05T17:26:07.997 回答