0
# Dictionary Operations
1
2
Bilingual dictionary functionality providing alternative translations, part-of-speech information, usage frequency data, back-translations, and contextual usage examples for translation pairs between supported language combinations.
3
4
## Capabilities
5
6
### Dictionary Entry Lookup
7
8
Returns alternative translations and linguistic information for source terms, including part-of-speech tags, confidence scores, and back-translation data.
9
10
```python { .api }
11
def lookup_dictionary_entries(
12
body: Union[List[str], List[InputTextItem], IO[bytes]],
13
*,
14
from_language: str,
15
to_language: str,
16
client_trace_id: Optional[str] = None,
17
**kwargs: Any
18
) -> List[DictionaryLookupItem]
19
```
20
21
**Parameters:**
22
- `body`: Terms to look up (strings, InputTextItem objects, or binary data)
23
- `from_language`: Source language code (must be supported for dictionary operations)
24
- `to_language`: Target language code (must be supported for dictionary operations)
25
- `client_trace_id`: Client-generated GUID for request tracking
26
27
**Returns:** List of dictionary lookup results with translations and metadata
28
29
### Dictionary Usage Examples
30
31
Returns contextual usage examples for specific translation pairs discovered through dictionary entry lookup.
32
33
```python { .api }
34
def lookup_dictionary_examples(
35
body: Union[List[DictionaryExampleTextItem], IO[bytes]],
36
*,
37
from_language: str,
38
to_language: str,
39
client_trace_id: Optional[str] = None,
40
**kwargs: Any
41
) -> List[DictionaryExampleItem]
42
```
43
44
**Parameters:**
45
- `body`: Translation pairs for example lookup
46
- `from_language`: Source language code
47
- `to_language`: Target language code
48
- `client_trace_id`: Client-generated GUID for request tracking
49
50
**Returns:** List of usage examples for each translation pair
51
52
### Usage Examples
53
54
```python
55
from azure.ai.translation.text import TextTranslationClient
56
from azure.ai.translation.text.models import DictionaryExampleTextItem
57
from azure.core.credentials import AzureKeyCredential
58
59
client = TextTranslationClient(
60
credential=AzureKeyCredential("your-api-key"),
61
region="your-region"
62
)
63
64
# Dictionary lookup for English to Spanish
65
lookup_response = client.lookup_dictionary_entries(
66
body=["fly"],
67
from_language="en",
68
to_language="es"
69
)
70
71
entry = lookup_response[0]
72
print(f"Source term: {entry.display_source}")
73
print(f"Normalized form: {entry.normalized_source}")
74
75
for translation in entry.translations:
76
print(f"\nTranslation: {translation.display_target}")
77
print(f"Part of speech: {translation.pos_tag}")
78
print(f"Confidence: {translation.confidence}")
79
print(f"Prefix word: '{translation.prefix_word}'")
80
81
print("Back-translations:")
82
for back_trans in translation.back_translations:
83
print(f" {back_trans.display_text} (frequency: {back_trans.frequency_count})")
84
85
# Get usage examples for specific translation pairs
86
examples_response = client.lookup_dictionary_examples(
87
body=[
88
DictionaryExampleTextItem(text="fly", translation="volar"),
89
DictionaryExampleTextItem(text="fly", translation="mosca")
90
],
91
from_language="en",
92
to_language="es"
93
)
94
95
for example_item in examples_response:
96
print(f"\nExamples for: {example_item.normalized_source} -> {example_item.normalized_target}")
97
98
for example in example_item.examples:
99
source_sentence = f"{example.source_prefix}{example.source_term}{example.source_suffix}"
100
target_sentence = f"{example.target_prefix}{example.target_term}{example.target_suffix}"
101
102
print(f" EN: {source_sentence.strip()}")
103
print(f" ES: {target_sentence.strip()}")
104
105
# Multi-term lookup
106
multi_lookup = client.lookup_dictionary_entries(
107
body=["house", "car", "book"],
108
from_language="en",
109
to_language="fr"
110
)
111
112
for i, entry in enumerate(multi_lookup):
113
print(f"\nTerm {i+1}: {entry.display_source}")
114
print(f"Translations: {len(entry.translations)}")
115
116
# Show most confident translation
117
if entry.translations:
118
best_translation = max(entry.translations, key=lambda t: t.confidence)
119
print(f"Best match: {best_translation.display_target} ({best_translation.confidence:.2f})")
120
```
121
122
## Input Types
123
124
### Dictionary Lookup Input
125
126
```python { .api }
127
class InputTextItem:
128
text: str # Term to look up in dictionary
129
```
130
131
### Example Lookup Input
132
133
```python { .api }
134
class DictionaryExampleTextItem:
135
text: str # Source term (normalized form from lookup)
136
translation: str # Target translation (normalized_target from lookup)
137
```
138
139
## Response Types
140
141
### Dictionary Lookup Results
142
143
```python { .api }
144
class DictionaryLookupItem:
145
display_source: str # Source term formatted for display
146
normalized_source: str # Normalized form for example lookups
147
translations: List[DictionaryTranslation] # Available translations
148
```
149
150
### Translation Information
151
152
```python { .api }
153
class DictionaryTranslation:
154
normalized_target: str # Normalized target term for examples
155
display_target: str # Target term formatted for display
156
pos_tag: str # Part-of-speech tag
157
confidence: float # Translation confidence (0.0 to 1.0)
158
prefix_word: str # Grammatical prefix (e.g., article)
159
back_translations: List[BackTranslation] # Reverse translations
160
```
161
162
### Back-Translation Data
163
164
```python { .api }
165
class BackTranslation:
166
normalized_text: str # Normalized back-translation
167
display_text: str # Back-translation formatted for display
168
num_examples: int # Available usage examples count
169
frequency_count: int # Usage frequency in training data
170
```
171
172
### Usage Example Results
173
174
```python { .api }
175
class DictionaryExampleItem:
176
normalized_source: str # Source term (matches input)
177
normalized_target: str # Target term (matches input)
178
examples: List[DictionaryExample] # Contextual examples
179
```
180
181
### Contextual Examples
182
183
```python { .api }
184
class DictionaryExample:
185
source_prefix: str # Text before source term
186
source_term: str # Source term in context
187
source_suffix: str # Text after source term
188
target_prefix: str # Text before target term
189
target_term: str # Target term in context
190
target_suffix: str # Text after target term
191
```
192
193
## Dictionary Language Support
194
195
Check which language pairs support dictionary operations:
196
197
```python
198
# Get dictionary-supported language pairs
199
response = client.get_supported_languages(scope="dictionary")
200
201
if response.dictionary:
202
for source_lang, lang_info in response.dictionary.items():
203
print(f"\nSource: {source_lang} ({lang_info.name})")
204
print("Available targets:")
205
206
for target in lang_info.translations:
207
print(f" -> {target.code} ({target.name})")
208
```
209
210
## Best Practices
211
212
### Lookup Workflow
213
1. Use `lookup_dictionary_entries()` to find translation options
214
2. Select appropriate translations based on confidence and context
215
3. Use `lookup_dictionary_examples()` with normalized forms for usage examples
216
4. Consider part-of-speech tags for disambiguation
217
218
### Term Normalization
219
- Dictionary lookups are case-insensitive
220
- Use normalized forms from lookup results for example queries
221
- Handle multi-word terms and phrases appropriately
222
223
### Frequency and Confidence
224
- Higher confidence scores indicate more reliable translations
225
- Frequency counts reflect usage patterns in training data
226
- Back-translations provide additional context for term selection
227
228
## Error Handling
229
230
```python
231
from azure.core.exceptions import HttpResponseError
232
233
try:
234
response = client.lookup_dictionary_entries(
235
body=["nonexistent"],
236
from_language="en",
237
to_language="unsupported" # Unsupported language pair
238
)
239
except HttpResponseError as error:
240
if error.error:
241
print(f"Error Code: {error.error.code}")
242
print(f"Message: {error.error.message}")
243
244
# Handle missing translations gracefully
245
lookup_result = client.lookup_dictionary_entries(
246
body=["raretechnicalterm"],
247
from_language="en",
248
to_language="es"
249
)
250
251
entry = lookup_result[0]
252
if not entry.translations:
253
print(f"No dictionary translations found for: {entry.display_source}")
254
else:
255
print(f"Found {len(entry.translations)} translation(s)")
256
```