我的代码在下面,只是尝试实现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']})
答案 0 :(得分:0)
您要附加out[v]
而不只是v
。您打算这样做:
for s in testdict:
for k,v in s.items():
out[k].append(v)
答案 1 :(得分:0)
out[v]
将始终返回空的list
。将其替换为v
:
...
out[k].append(out[v])
那么out
的值将是:
defaultdict(<type 'list'>, {'global': ['0134567890'], 'local': ['9134567890', '9134567890'], 'others': ['9034567890', '9034590']})