为什么我的代码无法将值附加到键

Why my code not working appending the values to key

我的代码在下面,只是试图实现 defaultdict

out = defaultdict(list)
testdict = [{'local': '9134567890'},
{'local': '9134567890'},
{'global': '0134567890'},
{'others': '9034567890'},
{'others': '9034590'}]
for s in testdict:
    for k,v in s.items():
            out[k].append(out[v])   
out

输出

defaultdict(list,
            {'0134567890': [],
             '9034567890': [],
             '9034590': [],
             '9134567890': [],
             'global': [[]],
             'local': [[], []],
             'others': [[], []]})

期望输出

defaultdict(<class 'list'>, {'local': ['9134567890', '9134567890'], 'global': ['0134567890'], 'others': ['9034567890', '9034590']})

您要附加 out[v] 而不仅仅是 v。您打算这样做:

for s in testdict:
    for k,v in s.items():
            out[k].append(v)   

out[v] 将始终 return 为空 list。将其替换为 v:

...
out[k].append(out[v])   

out 的值将是:

defaultdict(<type 'list'>, {'global': ['0134567890'], 'local': ['9134567890', '9134567890'], 'others': ['9034567890', '9034590']})