How to make QGIS abbreviate labels with a dictionary?

So the way I would do this is to create a custom expression function using Python and then we can do exactly what we need. I wrote about custom expression functions in one of my blog posts but here is how I would do it

from qgis.utils import qgsfunction

lookups = {'Wasserfall': 'Wssf.',
           'CascatA': 'Casc.' }

@qgsfunction(1, "String")
def abbrev(values, feature, parent):
    # The first value is our string to be changed
    value = values[0]
    # return the short version of the string
    words = value.split()
    newwords = []
    for word in words:
        newword = lookups.get(word, word)
        newwords.append(newword)
    return " ".join(newwords)

To use this function you can simply run it in the Python console, or a more permanent way is to add it to your .qgis2\python\startup.py file which gets run each time QGIS loads.

You will now find the function in the expression dialog and it can be used like this:

abbrev("nome1") || '$' || abbrev("nome2")

Complement to answer @Nathan W For french accent and UTF-8 encoding, to NathanW's answer, i had to add # -*- coding: utf-8 -*- in the head of the code.

NOW in 2.18: A new feature 'Substitution list support for labeling' More informations here.

Tags:

Labeling

Qgis