lundi 25 novembre 2019

What is the community preferred Python design pattern for accumulating values in a dictionary? [duplicate]

This question already has an answer here:

I often find myself writing this pattern for accumulating counts about a thing in a dictionary. In this case, I'm gathering up host hardware information for a datacenter application, and the pattern is the same I have often used.

Today, I was wondering if there is a better way (more Pythonic) to construct this pattern?

I did take a look around S.O. the most common result is using append on a list to add things which do not exist, but that does not address how to do an accumulator in a dictionary where the incoming key/value may or may not exist in the dictionary already.

hardware_types = []
for host in hosts:
    hardware_type = hosts[host]['hardware_type'])
    if hardware_type in hardware_types:
        hardware_types[hardware_type] += 1
    else:
        hardware_types[hardware_type] = 1

Thanks, Bob

Aucun commentaire:

Enregistrer un commentaire