Search code examples
pythonlistpython-3.xdictionarynested-loops

Replacing items in a dictionary of lists in Python


I am new to python and programming and need some help replacing items in a dictionary of lists. I would like to replace None with 'None' in the 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 is as follows:

new_dict = {}

for i in dict: #This accesses each dictionary key.
    temp = []
    for j in dict[i]: #This iterates through the inner lists
        if j is 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 a way to do this in a fewer lines of code or more efficiently using list comprehension or other methods? Should nested for loop (as I have it in my code) be avoided? Thanks.

Using Python 3.4.1


Solution

  • Use a dictionary comprehension:

    >>> {k:[e if e is not None else 'None' for e in v] for 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 a dict dict since it will mask the built in function by that name.


    If you have huge dicts or lists, you may want to modify your data in place. If so, this may be the most efficient:

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