dictionary - modify the dict on Python -


here data format:

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

i want original_data this:

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

would mind helping me?

use loop, adding items nested dictionaries:

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

the dict.setdefault() adds second argument default if key (the first argument) not yet present, returns value key. lets build nested dictionaries grouped d['year'] values.

demo:

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

you use collections.defaultdict() object take care of creating new nested dictionaries per key:

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

defaultdict subclass of dict; can 'reset' auto-value-creation behaviour setting defaultdict.default_factory none, after it'll act regular dictionary again:

>>> collections import defaultdict >>> new_data = defaultdict(dict) >>> 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 

Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -