0

I want to create the new dictionary that contents a dictionary with lists. My code is:

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)

What I got. I got the same list in every dictionary despite the fact that I used different keys.

My output is: {'FTP Download': {'MS1': [0, 1, 2]}, 'HTTP': {'MS1': [0, 1, 2]}, 'FTP Upload': {'MS1': [0, 1, 2]}}

What is the right way to create a blank dictionary from keys?

DSM
  • 342,061
  • 65
  • 592
  • 494
smirnoffs
  • 652
  • 1
  • 7
  • 14

1 Answers1

1

I'd simply use a dict comprehension instead:

>>> 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': []}}

Since fromkeys uses the value v for each key, in received = dict.fromkeys(SERVICES , {'MS1':[]}) there's really only one MS1 dictionary involved, which is what you noticed:

>>> received = dict.fromkeys(SERVICES , {'MS1':[]})
>>> received.values()
dict_values([{'MS1': []}, {'MS1': []}, {'MS1': []}])
>>> [id(v) for v in received.values()]
[141458940, 141458940, 141458940]
DSM
  • 342,061
  • 65
  • 592
  • 494