Dictionary Element Value in Python
To retrieve the value of an element from a dictionary, you need to access its key.
Let us have the following dictionary:
dct = {
'a': 1,
'b': 2,
'c': 3
}
Let's derive the first element from it. To do this, after the dictionary name, we specify the key name in square brackets:
print(dct['a']) # 1
If you access a key that is not in the dictionary, an error will be returned:
print(dct['x']) # will display an error
You can also store the dictionary key in a variable:
key = 'a'
print(dct[el]) # 1
Given a dictionary:
dct = {
'x': 1,
'y': 2,
'z': 3
}
Print each element of this dictionary.
Given a dictionary:
dct = {
'a': 1,
'b': 2,
'c': 3
}
Derive from it the number 2.
Given a dictionary:
dct = {
'x': 1,
'y': 2,
'z': 3
}
Given a variable:
key = 'x'
Print the element whose key is stored in the variable.
Given a dictionary:
dct = {
'a': 5,
'b': 10,
'c': 15
}
Sequentially derive all the values from it and get their sum.
Given a dictionary:
dct = {
1: 'a',
2: 'b',
3: 'c'
}
Write the code to get the following string:
'abc'