Search code examples
pythondefaultdict

How to write defaultdict in more pythonic way?


How do I write this in Pythonic way : counts_to_display is a defaultdict(dict) which has following data:

defaultdict(<type 'dict'>,
            {'server01': {'metric1': 9},
             'server02': {'metric1': 12},
             'server03': {'metric3': 8}, 
             'server04': {'metric1': 11, 'metric2': 7}
            })



headers = []
for count in counts_to_display:
        for name in counts_to_display[count]:
                if name not in headers:
                        headers.append(name)

I need to print everything in a table:

Server   Metric1 Metric2 Metric3
server01    9       0       0
server02    12       0       0
server03    0       0       8
server04    11       7       0

Solution

  • Here's one solution:

    headers = {key for count in counts_to_display.values() for key in count}
    

    I'm using a set instead of a list since we're working with a dictionary as input, which has arbitrary ordering anyway, so it wouldn't make sense to want to keep ordering intact, and sets automatically take care of deduplication for us, while being more performant for certain operations, too.

    You could use the following, too:

    import itertools
    headers = set(itertools.chain.from_iterable(counts_to_display.values()))