Programming with Python Class 9

Data Structures – Dictionaries

 

A dictionary is a sequence of key pairs, a value that can be of any type.

They are used to search the sequence associatively for a key rather than an index as in lists.

Typical use is to implement a dictionary between two languages

 

Example

Dictionary to translate from Spanish to English

esp_ing = {‘one’: ‘one’, ‘two’: ’two’, ‘three’: ‘three’}

 

The dictionary is indicated by brackets {} and the elements separated by commas.

Keep in mind that the order of the keys, value is not stored as defined.

In the dictionary we can search by the key

 

Example

esp_ing [‘dos’] would be ‘two’

 

Operations on dictionaries

len (d) returns the number of dictionary elements

d.values ​​() returns a list with the dictionary values ​​(without the keys)

d.keys () returns a list with the dictionary keys (without the values)

c in d returns True if the key c is in the dictionary

d [c] = v if the key c is in the dictionary associates the value v with the key c

if c is not in the dictionary add the key c and associate the value v

 

Example: Count words from a text

A very common use of dictionaries is to count the words in a text or paragraph.

text = ” ‘this is a test text to count the words with a dictionary this text does not have many words’ ”

counters = dict ()
words = text.split ()
for word in words:
if word not in counters:
counters [word] = 1
else:
counters [word] = counters [word] +1

print (counters)

 

1 an empty counters dictionary is created with dict ()

2 the words are extracted from the text with text.split () and the words are put in the list

3 the words in the list are traversed

4 if the word is not as a key in the dictionary, the word is added as a key and the value 1 is associated

7 if the word is already in the dictionary its counter is increased

 

If we run the example above, something like

{‘this’: 1,’ is’: 1, ‘a’: 2, ‘text’: 2, ‘from’: 1, ‘proofs’: 1,’ for ‘: 1,’ count ‘: 1,’ the ‘: 1,’ words’: 2, ‘with’: 1, ‘dictionary’: 1, ‘this’: 1,’ no ‘: 1,’ has’: 1, ‘many’: 1}

 

Leave a Reply

Your email address will not be published. Required fields are marked *