Check If a Given Key Already Exists in a Dictionary and Increment It

Check if a given key already exists in a dictionary and increment it

You are looking for collections.defaultdict (available for Python 2.5+). This

from collections import defaultdict

my_dict = defaultdict(int)
my_dict[key] += 1

will do what you want.

For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use

if key in my_dict:
my_dict[key] += 1
else:
my_dict[key] = 1

Question about increment a key value in Python dictionary

You are looping through your list so the values you are checking are 'a' then 'b' and so on. Each one of those doesn't exist in the dict yet so it enters the if clause and does: mydict[item] = 1.
If you want to see the values getting updated you need to go over the same key more than once.

Check if dict gets consecutive incremental counters

One way you might want this to happen is to check when you increment a value in dict:

for period in range(number_periods):
if value > mean_value:
dict[key] += 1 ​
v = dict[key]
v3 = v//3
if v3 > 0:
new_dict[key] = v3

Python : List of dict, if exists increment a dict value, if not append a new dict

That is a very strange way to organize things. If you stored in a dictionary, this is easy:

# This example should work in any version of Python.
# urls_d will contain URL keys, with counts as values, like: {'http://www.google.fr/' : 1 }
urls_d = {}
for url in list_of_urls:
if not url in urls_d:
urls_d[url] = 1
else:
urls_d[url] += 1

This code for updating a dictionary of counts is a common "pattern" in Python. It is so common that there is a special data structure, defaultdict, created just to make this even easier:

from collections import defaultdict  # available in Python 2.5 and newer

urls_d = defaultdict(int)
for url in list_of_urls:
urls_d[url] += 1

If you access the defaultdict using a key, and the key is not already in the defaultdict, the key is automatically added with a default value. The defaultdict takes the callable you passed in, and calls it to get the default value. In this case, we passed in class int; when Python calls int() it returns a zero value. So, the first time you reference a URL, its count is initialized to zero, and then you add one to the count.

But a dictionary full of counts is also a common pattern, so Python provides a ready-to-use class: containers.Counter You just create a Counter instance by calling the class, passing in any iterable; it builds a dictionary where the keys are values from the iterable, and the values are counts of how many times the key appeared in the iterable. The above example then becomes:

from collections import Counter  # available in Python 2.7 and newer

urls_d = Counter(list_of_urls)

If you really need to do it the way you showed, the easiest and fastest way would be to use any one of these three examples, and then build the one you need.

from collections import defaultdict  # available in Python 2.5 and newer

urls_d = defaultdict(int)
for url in list_of_urls:
urls_d[url] += 1

urls = [{"url": key, "nbr": value} for key, value in urls_d.items()]

If you are using Python 2.7 or newer you can do it in a one-liner:

from collections import Counter

urls = [{"url": key, "nbr": value} for key, value in Counter(list_of_urls).items()]

Increment a key value in a list of dictionaries

You could use a simple for loop with enumerate and update in-place the id keys in the dictionaries:

for new_id, d in enumerate(current_list_d, start=1):
d['id'] = new_id

current_list_d
[{'id': 1, 'name': 'Paco', 'age': 18},
{'id': 2, 'name': 'John', 'age': 20},
{'id': 3, 'name': 'Claire', 'age': 22}]

Increasing value for key which is existing in dictionary

You need to use the indexer property:

if (!concordanceDictionary.ContainsKey(word))
{
concordanceDictionary.Add(word, 1);
}
else
{
concordanceDictionary[word]++;
}


Related Topics



Leave a reply



Submit