Filter a dictionary using python list comprehension

  • Dictionaries are items grouped as key-value pairs enclosed within {}. List comprehension can be used to filter dictionaries.

    Output can be keys or values only or both keys and values. Filter conditions can also be applied on both keys and values.
    Refer sample below, which has dictionaries of numbers, dates and strings.

    Copied
    from datetime import datetime
    
    numdict = { 1:5, 2:10, 3:20, 4:30, 5:40 }
    #Filter numbers from dict
    filterednumdict = { key:val for key, val in numdict.items() if key > 3 }
    print(filterednumdict)
    
    strdict = { 'n1':'James', 'n2':'Rory', 'n3':'Kevin'}
    #Filter names
    filteredstrdict = { key:val for key, val in strdict.items() if (val == 'Rory' or val == 'Kevin')}
    print(filteredstrdict)
    
    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.strptime(val, '%Y/%m/%d') for key, val in datedict.items()}
    #Apply filter by month
    filtereddates = { key:val for key, val in dtitems.items() if val.month == 1}
    #Convert datetime to str dates, if needed
    dates2str = { key:datetime.strftime(val, '%Y/%m/%d') for key, val in filtereddates.items()}
    print(dates2str)
    
    Output:
      {4: 30, 5: 40}
      {'n2': 'Rory', 'n3': 'Kevin'}
      {1: '2021/01/02', 2: '2021/01/15'}

    If dates are in different formats, refer below link.
    Filter a list of string dates in different formats

  • Multi-dimensional dictionaries

    Dictionaries are unhashable objects and can't have unhashable objects within it.
    So multi-dimensional dictionaries are not possible.
    Lists or tuples can be provided as the values of a dictionary item. By applying some additional logic, we can filter those also.

Absolute Code Works - Python Topics