Updating dictionary items using python list comprehension

  • Dictionaries are items grouped as key-value pairs enclosed within {}. It is possible to update keys or values of a dictionary using List comprehension.

    This is particularly useful, if we need to make any common changes across all values or keys within the dictionary. Or, if we have to edit a set of values matching a particular condition.
    Refer sample below, which has dictionaries of numbers, dates and strings.

    Copied
    import datetime
    
    numdict = { 1:5, 2:10, 3:20, 4:30, 5:40 }
    updateddict = { key+2:val+10 for key, val in numdict.items() if key > 3 }
    print(updateddict)
    
    strdict = { 'n1':'James', 'n2':'Rory', 'n3':'Kevin'}
    updateddict = { key:val + ' SS' for key, val in strdict.items() if (val == 'Rory' or val == 'Kevin')}
    print(updateddict)
    
    datedict = { 1:'2021/1/2', 2:'2021/1/15', 3:'2022/4/1', 4:'2022/5/2'}
    #Convert string dates to datetime object
    dtitems = { key:datetime.datetime.strptime(val, '%Y/%m/%d') for key, val in datedict.items()}
    #Add 1 year to each date
    filtereddates = { key:val+datetime.timedelta(days=365) for key, val in dtitems.items()}
    #Convert datetime to str dates, if needed
    dates2str = { key:datetime.datetime.strftime(val, '%Y/%m/%d') for key, val in filtereddates.items()}
    print(dates2str)
    
    Outputs:
    {
    	6: 40,
    	7: 50
    }
    
    {
    	'n2': 'Rory SS',
    	'n3': 'Kevin SS'
    }
    
    {
    	1: '2022/01/02',
    	2: '2022/01/15',
    	3: '2023/04/01',
    	4: '2023/05/02'
    }
    
  • Updating lists within a dictionary

    Below sample contains a list as the value for each dictionary item.
    Check how to update the lists within a dictionary.

    Copied
    strdict = { 'n1': [10, 20, 30], 'n2': [40, 50, 60], 'n3': [70, 80, 90]}
    updateddict = { key:[val[0] + 100, val[1], val[2]] for key, val in strdict.items() }
    print(updateddict)
    
    Outputs:
    {
    	'n1': [110, 20, 30],
    	'n2': [140, 50, 60],
    	'n3': [170, 80, 90]
    }
    
Absolute Code Works - Python Topics