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

How do I find out if a key in a dictionary has already been set to a non-None value?

I want to increment the value if there's already one there, or set it to 1 otherwise:

my_dict = {}

if my_dict[key] is not None:
  my_dict[key] = 1
else:
  my_dict[key] += 1


Asked by: David257 | Posted: 30-11-2021






Answer 1

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

Answered by: Aston130 | Posted: 01-01-2022



Answer 2

I prefer to do this in one line of code.

my_dict = {}

my_dict[some_key] = my_dict.get(some_key, 0) + 1

Dictionaries have a function, get, which takes two parameters - the key you want, and a default value if it doesn't exist. I prefer this method to defaultdict as you only want to handle the case where the key doesn't exist in this one line of code, not everywhere.

Answered by: John132 | Posted: 01-01-2022



Answer 3

I personally like using setdefault()

my_dict = {}

my_dict.setdefault(some_key, 0)
my_dict[some_key] += 1

Answered by: Jared676 | Posted: 01-01-2022



Answer 4

You need the key in dict idiom for that.

if key in my_dict and not (my_dict[key] is None):
  # do something
else:
  # do something else

However, you should probably consider using defaultdict (as dF suggested).

Answered by: Kirsten605 | Posted: 01-01-2022



Answer 5

To answer the question "how can I find out if a given index in that dict has already been set to a non-None value", I would prefer this:

try:
  nonNone = my_dict[key] is not None
except KeyError:
  nonNone = False

This conforms to the already invoked concept of EAFP (easier to ask forgiveness then permission). It also avoids the duplicate key lookup in the dictionary as it would in key in my_dict and my_dict[key] is not None what is interesting if lookup is expensive.

For the actual problem that you have posed, i.e. incrementing an int if it exists, or setting it to a default value otherwise, I also recommend the

my_dict[key] = my_dict.get(key, default) + 1

as in the answer of Andrew Wilkinson.

There is a third solution if you are storing modifyable objects in your dictionary. A common example for this is a multimap, where you store a list of elements for your keys. In that case, you can use:

my_dict.setdefault(key, []).append(item)

If a value for key does not exist in the dictionary, the setdefault method will set it to the second parameter of setdefault. It behaves just like a standard my_dict[key], returning the value for the key (which may be the newly set value).

Answered by: Oliver945 | Posted: 01-01-2022



Answer 6

Agreed with cgoldberg. How I do it is:

try:
    dict[key] += 1
except KeyError:
    dict[key] = 1

So either do it as above, or use a default dict as others have suggested. Don't use if statements. That's not Pythonic.

Answered by: Walter449 | Posted: 01-01-2022



Answer 7

As you can see from the many answers, there are several solutions. One instance of LBYL (look before you leap) has not been mentioned yet, the has_key() method:

my_dict = {}

def add (key):
    if my_dict.has_key(key):
        my_dict[key] += 1
    else:
        my_dict[key] = 1

if __name__ == '__main__':
    add("foo")
    add("bar")
    add("foo")
    print my_dict

Answered by: Paul472 | Posted: 01-01-2022



Answer 8

A bit late but this should work.

my_dict = {}
my_dict[key] = my_dict[key] + 1 if key in my_dict else 1

Answered by: Patrick793 | Posted: 01-01-2022



Answer 9

The way you are trying to do it is called LBYL (look before you leap), since you are checking conditions before trying to increment your value.

The other approach is called EAFP (easier to ask forgiveness then permission). In that case, you would just try the operation (increment the value). If it fails, you catch the exception and set the value to 1. This is a slightly more Pythonic way to do it (IMO).

http://mail.python.org/pipermail/python-list/2003-May/205182.html

Answered by: Michelle893 | Posted: 01-01-2022



Answer 10

This isn't directly answering the question, but to me, it looks like you might want the functionality of collections.Counter.

from collections import Counter

to_count = ["foo", "foo", "bar", "baz", "foo", "bar"]

count = Counter(to_count)

print(count)

print("acts just like the desired dictionary:")
print("bar occurs {} times".format(count["bar"]))

print("any item that does not occur in the list is set to 0:")
print("dog occurs {} times".format(count["dog"]))

print("can iterate over items from most frequent to least:")
for item, times in count.most_common():
    print("{} occurs {} times".format(item, times))

This results in the output

Counter({'foo': 3, 'bar': 2, 'baz': 1})
acts just like the desired dictionary:
bar occurs 2 times
any item that does not occur in the list is set to 0:
dog occurs 0 times
can iterate over items from most frequent to least:
foo occurs 3 times
bar occurs 2 times
baz occurs 1 times

Answered by: Chester440 | Posted: 01-01-2022



Answer 11

Here's one-liner that I came up with recently for solving this problem. It's based on the setdefault dictionary method:

my_dict = {}
my_dict[key] = my_dict.setdefault(key, 0) + 1

Answered by: Julian705 | Posted: 01-01-2022



Answer 12

I was looking for it, didn't found it on web then tried my luck with Try/Error and found it

my_dict = {}

if my_dict.__contains__(some_key):
  my_dict[some_key] += 1
else:
  my_dict[some_key] = 1

Answered by: Kristian232 | Posted: 01-01-2022



Similar questions

python - How to add or increment a dictionary entry?

I'm currently re-engaging with Python after a long absence and loving it. However, I find myself coming across a pattern over and over. I keep thinking that there must be a better way to express what I want and that I'm probably doing it the wrong way. The code that I'm writing is in the following form: # foo is a dictionary if foo.has_key(bar): foo[bar] += 1 else: foo[bar] = 1


Python - Increment dictionary values

I have this nested dictionary: playlist = {u'user1': {u'Roads': 1.0, u'Pyramid Song': 1.0, u'Go It Alone': 1.0}} and I'm trying to increment its float values by 1.0: user = playlist.keys()[0] counts = playlist[user].values() for c in counts: c += 1.0 I've come this far. now, how do I update


Python increment values in a dictionary

I am trying to count every word from text files and appending the word and count to a dictionary as the key-value pairs. It throws me this error: if key not in wordDict: TypeError: unhashable type: 'list' Also, I am wondering of .split() is good because my text files contain different punctuation marks. fileref = open(mypath + '/' + i, 'r') wordDict = {} for line in fileref.readlines(): key = line.split...


python - Increment dictionary in a loop:

I need to count how many times a given number os text patterns appears in a log file and store this in a dictionary. My problem is that my code is counting all entries of the file to every kind of text pattern. The log file looks like this: What i doing wrong? >Feb 1 00:00:02 bridge kernel: INBOUND TCP: IN=br0 PHYSIN=eth0 OUT=br0 >PHYSOUT=eth1 SRC=XXX.XXX.XXX.XXX DST=XXX.XXX.X...


python - Loop over list and increment with values to dictionary

I have a list of this format: some_list = [[-5, 1000], [0, 600], [50, 600], [100,700], [170,650], [190,700]] and the function return should be a resulting dict with keys -5, -4, -3 ... and with values as the sum of increments up to each key. so for example above should be -5 : 0 , -4 : 1000, -3 : 2000, -1 : 3000, 0 : 4000, 1 : 4600 a...


python - Get Dictionary Keys From NumPy Array and Values From Increment

I have a large NumPy array (with 100,000,000 elements) that has unique and sorted values. The array may be generated with inefficiently with something like this (it will eat up your memory since the array is large but my array is derived efficiently from another source). import numpy as np x = np.random.choice(9509413522, size=100_000_000, replace=False) # this will take a ton of memory! x = np.sort(x)


How to increment value in dictionary using python

I have these lines inside text file: 2018-11-06 16:52:01.901| on thread[140447603222272 c0s0]| IP[192.168.0.244:5000]| master| 192.168.0.244| omer| (stmt : 0) | admin| Success 2018-11-06 16:52:15.160| on thread[140447603222272 c0s1]| IP[192.168.0.244:5001]| master| 192.168.0.244| userAdmin| (stmt : 1) | admin| Success 2018-11-06 16:52:27.351| on thread[140447603222272 c0s3]| IP[192.168.0.244:5000]| master...


python - Auto increment same values in dictionary

I have a dictionary: {'someKey1': 1, 'someKey2': 1, 'someKey3': 1, 'someKey4': 3, 'someKey5': 4, 'someKey6': 4, 'someKey7': 2} Output im trying to get is a dictionary with auto incremented values like so: {'someKey1': 1, 'someKey2': 2, 'someKey3': 3, 'someKey4': 5, 'someKey5': 7, 'someKey6': 6, 'someKey7': 4} Values in someKey1 - someKey3 don't matter as long ...


loops - How do I increment a value in a python dictionary?

Closed. This question needs details or clarity. It ...


python - How to increment the values in a dictionary without using a loop?

For example I have the following set up: dic = {"A":0, "B":0, "C":0} tokens = ["A", "B", "C", "C", "D", "E", "F"] If the element in the token exists in the dictionary keys, increment the value by 1. How do I do this without using the loop? I have the following for loop ri...


python - How to add or increment a dictionary entry?

I'm currently re-engaging with Python after a long absence and loving it. However, I find myself coming across a pattern over and over. I keep thinking that there must be a better way to express what I want and that I'm probably doing it the wrong way. The code that I'm writing is in the following form: # foo is a dictionary if foo.has_key(bar): foo[bar] += 1 else: foo[bar] = 1


dictionary - how to increment tuple values and search a string in a loop in python

I have this code. arfffile = [] inputed = raw_input("Enter Evaluation for name including file extension...") reader = open(inputed, 'r') verses = [] for line in reader: verses.append(line) for line in verses: if line.split('@') == "@": verses.pop(line) numclusters = int(raw_input("Enter the number of clusters")) clusters = {} for i in range(1,numclusters+1): clusters["cluster"...


dictionary - Increment items in nested python dict

I have a nested Python Dict and I am trying to take values from a list and then iterate them into a Dict's values as such: for row in rows: Dict[A][AA][AAA] += 1 However, when I print my dict, it appears to be adding all of the increments to all of the Dict entries. By which I mean that instead of this: {KeyA:{KeyAA:{KeyAAA:5}}} {KeyB:{KeyBB:{KeyBBB:10}}}


Python - How to modify dictionary values - increment or decrement by an integer value

Have a problem trying to add or subtract an integer value from all values in a dictionary and returning the modified dictionary. Below is my Python code: def increment(dictionary): for entry in dictionary: dictionary[entry] += 1 ## or -= 1 return dictionary Got this error code but don't know how to overcome it: TypeError: unsupported operand type(s) for +=: 'dict' and 'int...


python read csv file as dictionary and sort and increment a counter

I hope someone point me in the right direction. From what I've read, I believe using a dictionary would best suit this need but I am by no means a master programmer and I hope someone can shed some light and give me a hand. This is the CSV file I have: 11362672,091914,100914,100.00,ITEM,11,N,U08 12093169,092214,101514,25.00,ITEM,11,N,U10 12162432,091214,101214,175.00,ITEM,11,N,U07 11362672,091914,100914,65....


python - Exclude repeated values from a dictionary and increment the 'qty' field accordingly

Considering '1', '2', '3', '4' are the indexes and everything else as the values of a dictionary in Python, I'm trying to exclude the repeating values and increment the quantity field when a dupicate is found. e.g.: Turn this: a = {'1': {'name': 'Blue', 'qty': '1', 'sub': ['sky', 'ethernet cable']}, '2': {'name': 'Blue', 'qty': '1', 'sub': ['sky', 'ethernet cable']}, '3': {'name': 'Green...


Increment Nested Python Dictionary

I hope my question isn't answered elsewhere. I have a question about incrementing the value in a nested dictionary. Here is the relevant section of code. import xlrd import xlsxwriter workbook = xlrd.open_workbook("sample.xlsx") rsheet = workbook.sheet_by_index(0) uniquenames = ["Smith", "Jones", "Mark"] varlist = ["x", "y", "z"] var = {} for x in varlist: var[x] = 0 for g in uniquenames: namerows...


Python: Increment value of dictionary stored in a list

Simple example here: I want to have a list which is filled with dictionaries for every type of animal. The print should look like this: dictlist_animals = [{'type':'horse','amount':2}, {'type':'monkey','amount':2}, {'type':'cat','amount':1}, {'type':'dog','amount':1}] Because some animals exist more than once I've ...


Increment value of integer in Python dictionary

So I write an app that counts amount of yellow cards in football matches through all the games of the tournament. So let's say I count all Brazil's goals and I need to increment the amount of yellow cards with each game I go through in a loop. So I have this dictionary cards_per_team_dictionary that looks like this: ['Brazil', 0] and I wan't to increment the int value with each game. I tr...


python - How to natively increment a dictionary element's value?

When working with Python 3 dictionaries, I keep having to do something like this: d=dict() if 'k' in d: d['k']+=1 else: d['k']=0 I seem to remember there being a native way to do this, but was looking through the documentation and couldn't find it. Do you know what this is?


sorting - In Python, how can you easily retrieve sorted items from a dictionary?

Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key? For example, you had this: d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}


Python dictionary from an object's fields

Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this: >>> class Foo: ... bar = 'hello' ... baz = 'world' ... >>> f = Foo() >>> props(f) { 'bar' : 'hello', 'baz' : 'world' } NOTE: It should not include methods. Only fields.


python - How do you retrieve items from a dictionary in the order that they're inserted?

Is it possible to retrieve items from a Python dictionary in the order that they were inserted?


python - How can I make a dictionary from separate lists of keys and values?

I want to combine these: keys = ['name', 'age', 'food'] values = ['Monty', 42, 'spam'] Into a single dictionary: {'name': 'Monty', 'age': 42, 'food': 'spam'}


python - Dictionary or If statements, Jython

I am writing a script at the moment that will grab certain information from HTML using dom4j. Since Python/Jython does not have a native switch statement I decided to use a whole bunch of if statements that call the appropriate method, like below: if type == 'extractTitle': extractTitle(dom) if type == 'extractMetaTags': extractMetaTags(dom)


Is a Python dictionary an example of a hash table?

One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?


python - Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?

The list sort() method is a modifier function that returns None. So if I want to iterate through all of the keys in a dictionary I cannot do: for k in somedictionary.keys().sort(): dosomething() Instead, I must: keys = somedictionary.keys() keys.sort() for k in keys: dosomething() Is there a pretty way to iterate t...


python - Interface to versioned dictionary

I have an versioned document store which I want to access through an dict like interface. Common usage is to access the latest revision (get, set, del), but one should be able to access specific revisions too (keys are always str/unicode or int). from UserDict import DictMixin class VDict(DictMixin): def __getitem__(self, key): if isinstance(key, tuple): docid, rev = key e...


python - List all words in a dictionary that start with <user input>

How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! Edit: I'm using python, but I assume that this is a fairly language-independent problem.


Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?

I have a list of variable names, like this: ['foo', 'bar', 'baz'] (I originally asked how I convert a list of variables. See Greg Hewgill's answer below.) How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values of the variables? {'foo': foo, 'bar': bar, 'baz': baz} Now that I'm re-aski...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top