如何通过键更新嵌套的字典?

时间:2018-08-08 16:00:36

标签: python python-3.x dictionary instance

假设一个人有这个话:

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

我需要创建另一个字典并更新特定键“ C1”,像这样:

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)

我应该这样:

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

但是我有这个:

 {
 '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)
    }
}

不幸的是,按键的两个字典是同时更新的,但是我希望分别进行更新。有人有建议吗?

2 个答案:

答案 0 :(得分:0)

尝试:

new_p['C1'] = t1
new_p['C2'] = t2

答案 1 :(得分:0)

尝试:

 <?php 
        if (politicalwp_redux('mt_header_is_donate_active') == 1) {
          # code...
          if (politicalwp_redux('mt_donations_page') != '') {
            $donation_id = politicalwp_redux('mt_donations_page');
            $donation_url = get_permalink( $donation_id );

            echo '<a href="'.esc_url($donation_url).'" class="donate-now">
                    '.esc_attr__('Join us', 'politicalwp').'
                  </a>';
          }elseif (politicalwp_redux('mt_donations_page_custom_url') != '') {
            $donation_url = politicalwp_redux('mt_donations_page_custom_url');
            echo '<a href="'.esc_url($donation_url).'" class="donate-now">
                    '.esc_attr__('Join us', 'politicalwp').'
                  </a>';
          }
        }
        ?>