Avoid duplicate key names by adding a suffix

I need my title to be called a key, the problem is that it can cause problems with duplicate keywords, how can I check if it exists and add -1 to the end, if so, or add -2 to the end, if - 1 exists.

keyName = "hello"
duplicates = Entry.get_by_key_name(keyName)
            if duplicates:
                keyName = keyName+("-1")

How to run a loop with the addition of 1 until I find a unique name?

any help much appreciated j

+3
source share
2 answers
keyName = "hello"

testName = keyName
suffix = 0
while Entry.get_by_key_name(testName):
  suffix += 1
  testName = "%s-%d" % (keyName, suffix)

keyName = testName
+3
source

A different way to think about a problem:

from itertools import imap, dropwhile, count

def make_name(i):
    stem = "foo"
    return stem if i == 0 else "{0}-{1}".format(stem, i)

def in_universe(name):
    return bool(Entry.get_by_key_name(name))

seq = dropwhile(in_universe, imap(make_name, count()))
keyName = seq.next()
+2
source

All Articles