'Get correct value between 3 values based on language
I have a fairly simple question but yet I don't know what the best and shortest solution to my problem is.
Just for example, I have these variables, name_nl, name_fr and name_en.
Based on language priority (en, nl, fr) I'd like to end up with only one field that I will put in my API.
So if name_en is empty, it should give me name_nl and if that one is empty aswell it should give me name_fr.
So for example:name_en = '' name_nl = 'België'name_fr = 'Belgique'
Desired outcome --> België
name_en = '' name_nl = ''name_fr = Belgique
Desired outcome --> Belgique
As a python rookie, I would just work with if statements, but because there are a lot more fields then just "name", I don't wan't to write a massive amount of code.
any tips?
Solution 1:[1]
Without knowing the full structure of the OP's code this may or may not be useful.
name_en = ''
name_nl = 'België'
name_fr = 'Belgique'
print(name_en or name_nl or name_fr)
name_en = ''
name_nl = ''
name_fr = 'Belgique'
print(name_en or name_nl or name_fr)
Output:
België
Belgique
Solution 2:[2]
use something like
def get_next(values):
next(s for s in values if s)
print(get_next([name_en, name_nl, name_fr]))
Solution 3:[3]
That's how I'd suggest to solve the issue, with some changes based on specific needs:
class Word:
langPriority = ['en', 'nl', 'fr']
def __init__(self, **kwargs):
self.translations = kwargs
@property
def get(self):
for lang in self.langPriority:
try:
if tr := self.translations[lang]:
return tr
except KeyError:
continue
name = Word(en = '', nl = 'België', fr = 'Belgique')
print(name.get)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Albert Winestein |
| Solution 2 | Numan Ijaz |
| Solution 3 | matszwecja |
