Changes

Jump to navigation Jump to search
1,434 bytes added ,  08:58, 6 April 2015
Line 84: Line 84:  
==== Tuple ====
 
==== Tuple ====
 
==== Dictionary ====
 
==== Dictionary ====
Key - Value pairs,
+
Key - Value pairs. They are called diferent in diferent languages:<br />
 +
dictionary[key] = value <br />
 +
 
 +
* Perl → Associative arrays
 +
* Java → Properties, Map or HashMap
 +
* C# →  Property bag
 +
<br />
 +
Declarationn and assigment:<br />
 +
There are two posible ways to declare them:
 +
* purse = dict()
 +
* puse = {}
 +
<source lang="python">
 +
purse = dict()
 +
purse['money'] = 12
 +
purse['candy'] = 3
 +
 
 +
print purse['money']
 +
</source>
 +
purse = {'money': 12, 'candy' = 3}<br />
 +
 
 +
'''get() method:'''<br />
 +
If you try to retrieve a value for a key that doesn't exist you would get a traceback error.<br />
 +
To avoid this you should use the get() method, that returns the default value if the key doesn't exist:
 +
purse.get(name, default_value)
 +
'''Other methods and functions'''<br />
 +
* list(purse) → Returns a list of keys.
 +
* dict.keys() → Returns a list of keys.
 +
* dict.values() →  Returns a list of values.
 +
* dict.items → Returns a list of tuples ( [(key, value), (key, value)...] )
 +
''' Word count using files and dictionarys'''<br />
 
<source lang="python">
 
<source lang="python">
 +
counts = dict()
 +
file_path = raw_input('Enter file name: ')
 +
file_handle = open(file_path, 'r')
 +
text = file_handle.read()
 +
words = text.split()
 +
 +
for word in words:
 +
    counts[word] = counts.get(word, 0) + 1
 +
 +
bigCount = None
 +
bigWord  = None
 +
for word, count in counts.items():
 +
    if bigCount is None or count > bigCount:
 +
        bigWord = word
 +
        bigCount = count
    +
print 'Most frequent word: ', bigWord, '\nFrequency: ', bigCount'
 
</source>
 
</source>
  

Navigation menu