修改Python上的dict

时间:2015-09-30 20:14:03

标签: python dictionary

以下是数据格式:

original_data = [{'year':2015, 'missing_number':25, 'station':3}, {'year':2015, 'missing_number':15, 'station':6}, {'year':2013,'missing_number':28, 'station':9}, {'year':2013,'missing_number':65, 'station':10} ]

我希望我的original_data是这样的:

new_data = {'2015': {3:25,6:15}, '2013': {9:28, 10:65}}

你介意帮帮我吗?

1 个答案:

答案 0 :(得分:4)

使用循环,将项添加到嵌套词典:

new_data = {}
for d in original_data:
    new_data.setdefault(d['year'], {})[d['station']] = d['missing_number']

如果键(第一个参数)尚不存在,dict.setdefault()将第二个参数添加为默认值,然后返回键的值。这使您可以构建按d['year']值分组的嵌套字典。

演示:

>>> original_data = [{'year':2015, 'missing_number':25, 'station':3}, {'year':2015, 'missing_number':15, 'station':6}, {'year':2013,'missing_number':28, 'station':9}, {'year':2013,'missing_number':65, 'station':10} ]
>>> new_data = {}
>>> for d in original_data:
...     new_data.setdefault(d['year'], {})[d['station']] = d['missing_number']
... 
>>> new_data
{2013: {9: 28, 10: 65}, 2015: {3: 25, 6: 15}}

您还可以使用collections.defaultdict() object来处理每个键创建新的嵌套词典:

from collections import defaultdict

new_data = defaultdict(dict)
for d in original_data:
    new_data[d['year']][d['station']] = d['missing_number']

defaultdictdict的子类;你可以重置'通过将defaultdict.default_factory设置为None来实现自动创建价值的行为,之后它会再次像常规词典一样行动:

>>> from collections import defaultdict
>>> new_data = defaultdict(dict)
>>> for d in original_data:
...     new_data[d['year']][d['station']] = d['missing_number']
... 
>>> new_data
defaultdict(<type 'dict'>, {2013: {9: 28, 10: 65}, 2015: {3: 25, 6: 15}})
>>> new_data.default_factory = None
>>> new_data[2020]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 2020