Anthony Aldea
Anthony Aldea

Reputation: 13

What is the easiest way to increment a dictionary without using a for-loop?

I am trying to improve my understanding about dictionary list comprehension. I have created a silly list, based on what is in my driveway:

car = ['Ram', 'Ford', "Jeep", 'Jeep', 'ram']

I can create a dictionary and loop through the list

cardict = dict()
for count in car:
    count = count.upper()
    cardict[count] = cardict.get(count, 0) + 1
print(cardict)

That returns

{'RAM': 3, 'DODGE': 1, 'FORD': 1}

I have also been trying to improve my understanding of comprehension. So, I have also tried using fromkeys() and get()

For example,

again = dict.fromkeys(cardict, 0) + 1

However, I am getting a Type Error. How can I go through the dictionary and increment items in a list? I am looking for the "Pythonic" way to do this, so I would assume that there is a way without creating a for loop. Is it possible?

Upvotes: 0

Views: 79

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177800

The "Pythonic" way is to use collections.Counter, but you'll still need a list comprehension or map to change the case:

>>> from collections import Counter
>>> car = ['Ram', 'Ford', "Jeep", 'Jeep', 'ram']
>>> Counter(car)
Counter({'Jeep': 2, 'Ram': 1, 'Ford': 1, 'ram': 1})
>>> Counter([x.upper() for x in car])
Counter({'RAM': 2, 'JEEP': 2, 'FORD': 1})
>>> Counter(map(str.upper,car))
Counter({'RAM': 2, 'JEEP': 2, 'FORD': 1})

Upvotes: 2

Related Questions