Replacing items in a dictionary of lists in Python -


i new python , programming , need replacing items in dictionary of lists. replace none 'none' in dictionary below:

dict = {'chester100': ['caesar, augustus', '05/10/2012', '09/09/2012', none],         'rochester102': ['henrich, norton', '08/18/2014', '12/17/2014', none],         'rochester100': ['caeser, julius', '08/18/2014', '12/17/2014', none],         'rochester101': [none, none, none, '08/18/2012']} 

my code follows:

new_dict = {}  in dict: #this accesses each dictionary key.     temp = []     j in dict[i]: #this iterates through inner lists         if j none:             temp.append('none')         else:             temp.append(j)         temp2 = {str(i):temp}         new_dict.update(temp2)      print(new_dict) 

yields

{'chester100': ['caesar, augustus', '05/10/2012', '09/09/2012', 'none'],  'rochester102': ['henrich, norton', '08/18/2014', '12/17/2014', 'none'],  'rochester100': ['caeser, julius', '08/18/2014', '12/17/2014', 'none'],  'rochester101': ['none', 'none', 'none', '08/18/2012']} 

is there way in fewer lines of code or more efficiently using list comprehension or other methods? should nested loop (as have in code) avoided? thanks.

using python 3.4.1

use dictionary comprehension:

>>> {k:[e if e not none else 'none' e in v] k,v in di.items()} {'rochester102': ['henrich, norton', '08/18/2014', '12/17/2014', 'none'], 'rochester100': ['caeser, julius', '08/18/2014', '12/17/2014', 'none'], 'rochester101': ['none', 'none', 'none', '08/18/2012'], 'chester100': ['caesar, augustus', '05/10/2012', '09/09/2012', 'none']} 

and don't name dict dict since mask built in function name.


if have huge dicts or lists, may want modify data in place. if so, may efficient:

for key, value in di.items():     i, e in enumerate(value):         if e none: di[key][i]='none'     

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -