How to convert dictionary values into list in Python / Django?
Question: In my Django template, I call this frequently:

    
    
    {% for name, address in directory.addressbook.items %}
      {% for street in address.list %}
        {{street.number}}
    

How do I create this as a filter? I've tried this, but it doesn't work.

In the template, I call:

    
    
    {{directory.addressbook.items|all_numbers}}
    

And in my filter definition I have:

    
    
    def all_numbers(data):
      number_list=[]
      if isinstance(data, dict):
        for name, address in data:
          for street in data.list():
            number_list.append(street)
        return number_list
    

But all I get returned is "[ ]". What am I doing wrong?


Answer: You need to register your function as a template filter. Also, this code will
need to be in a module and then imported into your template as such...

    
    
    # custom_filters.py
    from django import template
    
    register = template.Library()
    
    
    @register.filter
    def all_numbers(data):
      number_list=[]
      if isinstance(data, dict):
        for name, address in data:
          for street in data.list():  # this will raise an exception
            number_list.append(street)
        return number_list
    
    # your-template.html
    {% load custom_filters %}
    
    {{ directory.addressbook.items|all_numbers }}
    

