Python 3.2中的dict.fromkeys方法

时间:2012-09-05 17:22:08

标签: python dictionary python-3.x

我想创建一个新的字典,其中包含带有列表的字典。我的代码是:

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]}}

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

1 个答案:

答案 0 :(得分: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]