嵌套字典上删除字典操作的奇怪行为

时间:2016-10-15 03:36:56

标签: python

impl<'a> Scope<'a> {
    pub fn spawn<F>(&mut self, f: F) where F: FnOnce() + Send + 'a {
        assert!(std::mem::size_of::<F>() <= 256);
        let mut x: [u8; 256] = [0; 256];
        unsafe { std::ptr::write(&mut x as *mut _ as *mut F, f); }
        let join_handle = thread::spawn(move || {
            let f: F = unsafe { std::mem::transmute_copy(&x) };
            f()
        });
        self.join_handles.push_back(join_handle);
    }
}

输出:

#!/usr/bin/python
import numpy as np

td={}
d = {}
for col in ['foo','bar','baz']:
    for row in ['a','b','c','d']:
        td.setdefault(row, np.random.randn())
        d.setdefault(col, td)

print d
del d['foo']['c']
print d

此处的意图是仅删除{'baz': {'a': -1.6340274257732716, 'c': 0.6674016962534858, 'b': 2.0410088421902652, 'd': -1.2602923734811284}, 'foo': {'a': -1.6340274257732716, 'c': 0.6674016962534858, 'b': 2.0410088421902652, 'd': -1.2602923734811284}, 'bar': {'a': -1.6340274257732716, 'c': 0.6674016962534858, 'b': 2.0410088421902652, 'd': -1.2602923734811284}} {'baz': {'a': -1.6340274257732716, 'b': 2.0410088421902652, 'd': -1.2602923734811284}, 'foo': {'a': -1.6340274257732716, 'b': 2.0410088421902652, 'd': -1.2602923734811284}, 'bar': {'a': -1.6340274257732716, 'b': 2.0410088421902652, 'd': -1.2602923734811284}} ,但所有d['foo']['c]都会在'c'内删除。不确定此论坛是否已经回复如果是,请指出我的答案。

1 个答案:

答案 0 :(得分:0)

您要设置d中的每个值以引用td的同一副本。如果您希望副本不同,则需要创建多个td字典。

试试这个:

#!/usr/bin/python
import numpy as np

d = {}
for col in ['foo','bar','baz']:
    td = {}
    for row in ['a','b','c','d']:
        td.setdefault(row, np.random.randn())
    d.setdefault(col, td)

print d
del d['foo']['c']
print d