0

Supposing that a have this dict:

s1 = ("P1", "S1", 600)
s2 = ("P2", "S2", 180)
s3 = ("P3", "S3", 180)

p = {
    'C1': {
        (2014, 1, 1, 1, 0, 0): s1,
        (2014, 1, 1, 2, 0, 0): s2,
        (2014, 1, 1, 3, 0, 0): s3,
        (2014, 1, 1, 4, 0, 0): s1,
        (2014, 1, 8, 1, 0, 0): s3,
        (2014, 1, 9, 1, 0, 0): s3,
        (2014, 1, 10, 1, 0, 0): s3,
        (2014, 1, 11, 1, 0, 0): s3},
    'C2': {
        (2014, 1, 1, 1, 0, 0): s2,
        (2014, 1, 1, 2, 0, 0): s3,
        (2014, 1, 1, 3, 0, 0): s2,
        (2014, 1, 1, 4, 0, 0): s2,
        (2014, 1, 8, 1, 0, 0): s1,
        (2014, 1, 9, 1, 0, 0): s1}
}

I need create another dict and update the specific key "C1", like that:

new_p = dict.fromkeys(p.keys(),{})

t1 = {(2017, 1, 1, 1, 0, 0): s2}
t2 = {(2018, 1, 1, 1, 0, 0): s1}

new_p['C1'].update(t1)
new_p['C2'].update(t2)

I was expected this:

 {
 'C2': 
    {
        (2017, 1, 1, 1, 0, 0): ('P2', 'S2', 180)
    },
 'C1': 
    {
        (2017, 1, 1, 1, 0, 0): ('P2', 'S2', 180)
    }
}

But I had this:

 {
 'C2': 
    {
        (2017, 1, 1, 1, 0, 0): ('P2', 'S2', 180), 
        (2018, 1, 1, 1, 0, 0): ('P1', 'S1', 600)
    },
 'C1': 
    {
        (2017, 1, 1, 1, 0, 0): ('P2', 'S2', 180),
        (2018, 1, 1, 1, 0, 0): ('P1', 'S1', 600)
    }
}

Unfortunately the two dict by key was updated at the same time, but I was expected update separately. Someone have a suggestion?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Andre Araujo
  • 2,348
  • 2
  • 27
  • 41
  • Or https://stackoverflow.com/questions/36253182/python-dict-fromkeys-generates-copies-of-list-instead-of-a-new-one – user202729 Aug 08 '18 at 16:03

2 Answers2

0

Try :

new_p['C1'] = t1
new_p['C2'] = t2
Matina G
  • 1,452
  • 2
  • 14
  • 28
  • While this code may answer the question, providing additional context regarding *how* and *why* it solves the problem would improve the answer's long-term value. – Alexander Aug 08 '18 at 17:00
0

Try:

new_p['C2'] = t1
new_p['C1'] = t1
Richard Rublev
  • 7,718
  • 16
  • 77
  • 121