Aman Deep Gautam
Aman Deep Gautam

Reputation: 8747

Pythonic way for checking if value exists in dictionary of dictionaries and taking corresponding actions

I have created a dictionary of dictionaries as:

from collections import defaultdict
d = defaultdict(dict)

Now I have some strings (let us call this set A) which have a dictionary of strings (as key) and integers (as value) corresponding to it. So the above data structure models this data completely.

Now I want to check if a string corresponding to a key in A exists in the dictionary. If it does not exist I want to add it and make its counter 1. If it already exists, I want to increment the counter.

Is there is pythonic way to do this?

Upvotes: 1

Views: 3178

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121554

If you have the key to the nested dict, you can use a simple in test:

if somestring in d[key]:
    d[key][somestring] += 1
else:
    d[key][somestring] = 1

but you could use a Counter instead:

from collections import defaultdict, Counter
d = defaultdict(Counter)

d[key][somestring] += 1

Like a defaultdict, a Counter provides a default value for missing keys, defaulting to 0.

Counters have other benefits; instead of looping over a set of strings and manually increasing the counter for those one by one, pass the whole sequence to the .update() method for the appropriate counter:

d[key].update(sequence_of_strings)

and the Counter will count them all for you.

The Counter class is what other languages might call a Multi-Set or Bag type. They support interesting comparison and arithmetic operations too, do make sure you read the documentation for the type.

Upvotes: 4

Bakuriu
Bakuriu

Reputation: 101919

As Lev Levitsky pointed out, what you want is to use a Counter. For example, assuming that you have this strings:

>>> the_strings = [
...     ('a', ('the', 'strings', 'in', 'the', 'dict')),
...     ('b', ('other', 'strings', 'in', 'the', 'dict', 'in', 'your', 'question'))
... ]

And you want to associate to 'a' a dict with the counts of that words, you can do:

>>> my_dict = defaultdict(Counter)
>>> for key, strings in the_strings:
...     my_dict[key].update(strings)
... 
>>> my_dict['a']['the']
2
>>> my_dict['b']['in']
2
>>> my_dict['b']['question']
1

If you want to increase a single value you can simply do:

>>> my_dict[the_string][the_word] += 1

Or you can automatically increase the count of every element in an iterable using the update method:

>>> my_dict[the_string].update(iterable_of_elements)

Upvotes: 1

Related Questions