22
Python Dictionaries.
Hello all, before we dive into today's article. I would like to inform you that I have been attending a four week python bootcamp organised by Data Science East Africa and Lux Tech Academy.
So far I have learnt all the basics of python some of which I have been writing about here. Additionally, we have also been introduced to Flask and FAST API and this week we shall be handling data science.
So far I have learnt all the basics of python some of which I have been writing about here. Additionally, we have also been introduced to Flask and FAST API and this week we shall be handling data science.
Now back to today's article.
Dictionary in Python is an ordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.
# creating an empty dictionary
dictionary = dict()
print(dictionary)
{}
The curly brackets represent an empty dictionary. To add an item to the dictionary we use the square brackets.
>>>dictionary['one'] = 'uno'
The above piece of code creates an item that maps from the key 'one' to the value 'uno'.
Printing the dictionary again gives a key-value pair with the key and value.
We can continue adding more items to the dictionary using the method demonstrated above.
Printing the dictionary again gives a key-value pair with the key and value.
{'one':'uno'}
.We can continue adding more items to the dictionary using the method demonstrated above.
>>> dictionary = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> print(dictionary)
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
>>>print(dictionary['one'])
'uno'
From above, we see that 'uno' is returned because we used it's key 'one' to access it.
To know the number of key-value pairs we use len() function.
To know the number of key-value pairs we use len() function.
>>>len(dictionary)
3
The in operator can be used to tell whether something appears as a key in the dictionary.
>>>'one' in dictionary
True
>>> 'uno' in dictionary
False
To check whether something appear as a value, you can use the method values to return a list of values and them use the in operator to find it.
>>>values = list(dictionary.values())
>>> 'uno' in values
True
word = 'brontosaurus'
d = dict()
for o in word:
if o not in d:
d[0] = 1
else:
d[0] = d[0] + 1
print(d)
# we get {'o':2}
This article is being updated.
22